{ "pages": [ { "page_number": 1, "text": "" }, { "page_number": 2, "text": "Kali Linux – Assuring Security \nby Penetration Testing\nMaster the art of penetration testing with Kali Linux\nLee Allen\nTedi Heriyanto\nShakeel Ali\n BIRMINGHAM - MUMBAI\n" }, { "page_number": 3, "text": "[ FM-2 ]\nKali Linux – Assuring Security by Penetration Testing\nCopyright © 2014 Packt Publishing\nAll rights reserved. No part of this book may be reproduced, stored in a retrieval \nsystem, or transmitted in any form or by any means, without the prior written \npermission of the publisher, except in the case of brief quotations embedded in \ncritical articles or reviews.\nEvery effort has been made in the preparation of this book to ensure the accuracy \nof the information presented. However, the information contained in this book is \nsold without warranty, either express or implied. Neither the authors, nor Packt \nPublishing, and its dealers and distributors will be held liable for any damages \ncaused or alleged to be caused directly or indirectly by this book.\nPackt Publishing has endeavored to provide trademark information about all of the \ncompanies and products mentioned in this book by the appropriate use of capitals. \nHowever, Packt Publishing cannot guarantee the accuracy of this information.\nFirst published: April 2011\nSecond Edition: April 2014\nProduction Reference: 2310314\nPublished by Packt Publishing Ltd.\nLivery Place\n35 Livery Street\nBirmingham B3 2PB, UK.\nISBN 978-1-84951-948-9\nwww.packtpub.com\nCover Image by Riady Santoso (dzign.art@gmail.com)\n" }, { "page_number": 4, "text": "[ FM-3 ]\nCredits\nAuthors\nLee Allen\nTedi Heriyanto\nShakeel Ali\nReviewers\nAlex Gkiouros\nNeil Jones\nAcquisition Editors\nHarsha Bharwani\nUsha Iyer\nRubal Kaur\nContent Development Editor\nSweny M. Sukumaran\nTechnical Editors\nMrunal Chavan\nPankaj Kadam\nGaurav Thingalaya\nCopy Editors\nJanbal Dharmaraj\nDipti Kapadia\nSayanee Mukherjee\nStuti Srivastava\nProject Coordinator\nSanchita Mandal\nProofreaders\nSimran Bhogal\nMaria Gould\nPaul Hindle\nIndexer\nHemangini Bari\nGraphics\nYuvraj Mannari\nAbhinash Sahu\nProduction Coordinator\nAlwin Roy\nCover Work\nAlwin Roy\n" }, { "page_number": 5, "text": "[ FM-4 ]\nAbout the Authors\nLee Allen is currently working as a security architect at a prominent university. \nThroughout the years, he has continued his attempts to remain up to date with \nthe latest and greatest developments in the security industry and the security \ncommunity. He has several industry certifications including the OSWP and has been \nworking in the IT industry for over 15 years.\nLee Allen is the author of Advanced Penetration Testing for Highly-Secured \nEnvironments: The Ultimate Security Guide, Packt Publishing.\nI would like to thank my wife, Kellie, and our children for allowing \nme to give the time I needed to work on this book. I would also \nlike to thank my grandparents, Raymond and Ruth Johnson, and \nmy wife's parents, George and Helen Slocum. I appreciate your \nencouragement and support throughout the years.\n" }, { "page_number": 6, "text": "[ FM-5 ]\nTedi Heriyanto currently works as a principal consultant in an Indonesian \ninformation security company. In his current role, he has been engaged with various \npenetration testing assignments in Indonesia and other countries. In his previous \nrole, he was engaged with several well-known business institutions across Indonesia \nand overseas. Tedi has an excellent track record in designing secure network \narchitecture, deploying and managing enterprise-wide security systems, developing \ninformation security policies and procedures, performing information security audits \nand assessments, and providing information security awareness training. In his \nspare time, he manages to research, learn, and participate in the Indonesian Security \nCommunity activities and has a blog http://theriyanto.wordpress.com. \nHe shares his knowledge in the security field by writing several information \nsecurity books.\nI would like to thank my family for supporting me during the whole \nbook-writing process. I would also like to thank my boss for trusting, \nhelping, and supporting me in my work. I would like to thank \nmy colleagues and customers for the great learning environment. \nThanks to the great people at Packt Publishing: Rubal Kaur, Sweny \nSukumaran, Joel Goveya, Usha Iyer, and Abhijit Suvarna, whose \ncomments, feedbacks, and support made this book development \nproject successful. Thanks to the technical reviewers, Alex Gkiouros \nand Neil Jones, who have provided their expertise, time, efforts, \nand experiences in reviewing the book's content. Last but not least, \nI would like to give my biggest thanks to the co-authors, Lee Allen \nand Shakeel Ali, whose technical knowledge, motivation, ideas, \nchallenges, questions, and suggestions made this book-writing \nprocess a wonderful journey. \n \nFinally, I would like to thank you for buying this book. I hope you \nenjoy reading the book as I enjoyed writing it. I wish you good luck \nin your information security endeavor.\n" }, { "page_number": 7, "text": "[ FM-6 ]\nShakeel Ali is a Security and Risk Management consultant at Fortune 500. \nPreviously, he was the key founder of Cipher Storm Ltd., UK. His expertise in the \nsecurity industry markedly exceeds the standard number of security assessments, \naudits, compliance, governance, and forensic projects that he carries out in day-to-day \noperations. He has also served as a Chief Security Officer at CSS Providers SAL. As a \nsenior security evangelist and having spent endless nights without taking a nap, he \nprovides constant security support to various businesses, educational organizations, \nand government institutions globally. He is an active, independent researcher who \nwrites various articles and whitepapers and manages a blog at Ethical-Hacker.net. \nAlso, he regularly participates in BugCon Security Conferences held in Mexico, \nto highlight the best-of-breed cyber security threats and their solutions from \npractically driven countermeasures.\nI would like to thank all my friends, reviewers, and colleagues \nwho were cordially involved in this book project. Special thanks \nto the entire Packt Publishing team and their technical editors and \nreviewers, who have given invaluable comments, suggestions, \nfeedbacks, and support to make this project successful. I also want \nto thank my co-authors, Lee Allen and Tedi Heriyanto, whose \ncontinual dedication, contributions, ideas, and technical discussions \nled to the production of such a useful product you see today. Last \nbut not least, thanks to my pals from past and present with whom \nthe sudden discovery never ends and their vigilant eyes that turn \nthe IT industry into a secure and stable environment.\n" }, { "page_number": 8, "text": "[ FM-7 ]\nAbout the Reviewers\nAlex Gkiouros is currently an independent IT professional who's been assigned \nvarious projects around Greece and has been working in the IT industry since 2006. \nHe holds two entry-level ISACA certifications, and he's studying for his CCNP. He \nis so passionate about what he does that he spends an inordinate amount of time in \nthe network security area, especially pentesting with Kali Linux or Backtrack. His \npersonal website or blog can be found at http://www.voovode.net/.\nNeil Jones is a security consultant, working for a global security company based \nin the UK. His goal was to work in the security industry from a young age and now \nhe has achieved that goal, while gaining multiple industry-recognized security \ncertifications along the way.\nHe eats, sleeps, and breathes security and is actively involved in security research to \nadvance his knowledge and to develop new open source tools in order to benefit the \nsecurity community.\n" }, { "page_number": 9, "text": "[ FM-8 ]\nwww.PacktPub.com\nSupport files, eBooks, discount offers and more\nYou might want to visit www.PacktPub.com for support files and downloads related \nto your book. \nDid you know that Packt offers eBook versions of every book published, with PDF \nand ePub files available? You can upgrade to the eBook version at www.PacktPub.\ncom and as a print book customer, you are entitled to a discount on the eBook copy. \nGet in touch with us at service@packtpub.com for more details.\nAt www.PacktPub.com, you can also read a collection of free technical articles, sign \nup for a range of free newsletters and receive exclusive discounts and offers on Packt \nbooks and eBooks.\nTM\nhttp://PacktLib.PacktPub.com \nDo you need instant solutions to your IT questions? PacktLib is Packt's online digital \nbook library. Here, you can access, read and search across Packt's entire library of \nbooks. \nWhy Subscribe?\n•\t\nFully searchable across every book published by Packt\n•\t\nCopy and paste, print and bookmark content\n•\t\nOn demand and accessible via web browser\nFree Access for Packt account holders\nIf you have an account with Packt at www.PacktPub.com, you can use this to access \nPacktLib today and view nine entirely free books. Simply use your login credentials \nfor immediate access.\n" }, { "page_number": 10, "text": "[ FM-9 ]\nDisclaimer\nThe content within this book is for educational purposes only. It is designed to help \nusers test their own system against information security threats and protect their IT \ninfrastructure from similar attacks. Packt Publishing and the authors of this book \ntake no responsibility for actions resulting from the inappropriate usage of learning \nmaterials contained within this book.\n" }, { "page_number": 11, "text": "" }, { "page_number": 12, "text": "[ FM-11 ]\nI would like to dedicate this book to my loving family for their kind support \nthroughout the years, especially to my niece, Jennifer, and nephews, Adan and \nJason, whose smiles are an inspiration and encouragement in my life; to my \nbrilliant teachers, the ones who turned an ordinary child into this superior, \nexcellent, and extraordinary individual; and to all my friends and colleagues, \nAmreeta Poran, Li Xiang, Fazza3, Sheikha Maitha, Touraj, Armin, Mada, Rafael, \nKhaldoun, Niel, Oscar, Serhat, Kenan, Michael, Ursina, Nic, Nicole, Andreina, \nAmin, Pedro, Juzer, Ronak, Cornel, Marco, Selin, Jenna, Yvonne, Cynthia, May, \nCorinne, Stefanie, Rio, Jannik, Carmen, Gul Naz, Stella, Patricia, Mikka, Julian, \nSnow, Matt, Sukhi, Tristan, Srajna, Padmanabhan, Radhika, Gaurav, Eljean \nDesamparado, Akeela, Naveed, Asif, Salman, and all those whom I have forgotten \nto mention here.\n - Shakeel Ali\nI would like to dedicate this book to God for the amazing gifts that have been given \nto me; to my beloved family for their support; to my wonderful teachers for being so \npatient in teaching me; to my best friends and colleagues for helping me out during \nthe years; to my excellent clients for trusting in me and giving me the chance to \nwork with you; to you, the reader, for buying this book and e-book.\n - Tedi Heriyanto\nI would like to dedicate this book to those of you that have provided the security \nindustry with the tools that empower us, the research that enlightens us, and the \nfriendships that sustain us.\n - Lee Allen\n" }, { "page_number": 13, "text": "" }, { "page_number": 14, "text": "Table of Contents\nPreface\t\n1\nPART I: Lab Preparation and Testing Procedures\nChapter 1: Beginning with Kali Linux\t\n9\nA brief history of Kali Linux\t\n9\nKali Linux tool categories\t\n10\nDownloading Kali Linux\t\n12\nUsing Kali Linux\t\n14\nRunning Kali using Live DVD\t\n14\nInstalling Kali on a hard disk\t\n15\nInstalling Kali on a physical machine\t\n15\nInstalling Kali on a virtual machine\t\n19\nInstalling Kali on a USB disk\t\n26\nConfiguring the virtual machine\t\n28\nVirtualBox guest additions\t\n28\nSetting up networking \t\n30\nSetting up a wired connection\t\n31\nSetting up a wireless connection\t\n32\nStarting the network service\t\n33\nConfiguring shared folders\t\n34\nSaving the guest machine state\t\n35\nExporting a virtual machine\t\n36\nUpdating Kali Linux\t\n37\nNetwork services in Kali Linux\t\n39\nHTTP\t\n39\nMySQL\t\n40\nSSH\t\n42\nInstalling a vulnerable server\t\n43\n" }, { "page_number": 15, "text": "Table of Contents\n[ ii ]\nInstalling additional weapons\t\n45\nInstalling the Nessus vulnerability scanner\t\n47\nInstalling the Cisco password cracker\t\n49\nSummary\t\n49\nChapter 2: Penetration Testing Methodology\t\n51\nTypes of penetration testing\t\n52\nBlack box testing\t\n52\nWhite box testing\t\n53\nVulnerability assessment versus penetration testing\t\n53\nSecurity testing methodologies\t\n54\nOpen Source Security Testing Methodology Manual (OSSTMM)\t\n56\nKey features and benefits\t\n57\nInformation Systems Security Assessment Framework (ISSAF)\t\n58\nKey features and benefits\t\n59\nOpen Web Application Security Project (OWASP) \t\n60\nKey features and benefits\t\n60\nWeb Application Security Consortium Threat Classification (WASC-TC)\t\n61\nKey features and benefits\t\n62\nPenetration Testing Execution Standard (PTES)\t\n63\nKey features and benefits\t\n64\nGeneral penetration testing framework\t\n64\nTarget scoping\t\n65\nInformation gathering\t\n65\nTarget discovery\t\n66\nEnumerating target\t\n66\nVulnerability mapping\t\n67\nSocial engineering\t\n67\nTarget exploitation\t\n67\nPrivilege escalation\t\n68\nMaintaining access\t\n68\nDocumentation and reporting\t\n68\nThe ethics\t\n69\nSummary\t\n70\nPART II: Penetration Testers Armory\nChapter 3: Target Scoping\t\n73\nGathering client requirements\t\n74\nCreating the customer requirements form\t\n75\nThe deliverables assessment form\t\n76\nPreparing the test plan\t\n76\nThe test plan checklist\t\n78\n" }, { "page_number": 16, "text": "Table of Contents\n[ iii ]\nProfiling test boundaries\t\n79\nDefining business objectives\t\n80\nProject management and scheduling\t\n81\nSummary\t\n82\nChapter 4: Information Gathering\t\n85\nUsing public resources\t\n86\nQuerying the domain registration information\t\n87\nAnalyzing the DNS records\t\n89\nhost\t\n90\ndig\t\n92\ndnsenum\t\n94\ndnsdict6\t\n97\nfierce\t\n98\nDMitry\t\n100\nMaltego\t\n102\nGetting network routing information\t\n110\ntcptraceroute\t\n110\ntctrace\t\n112\nUtilizing the search engine\t\n112\ntheharvester\t\n113\nMetagoofil\t\n114\nSummary\t\n118\nChapter 5: Target Discovery\t\n119\nStarting off with target discovery\t\n119\nIdentifying the target machine\t\n120\nping\t\n120\narping\t\n123\nfping\t\n124\nhping3\t\n127\nnping\t\n130\nalive6\t\n132\ndetect-new-ip6\t\n133\npassive_discovery6\t\n134\nnbtscan\t\n134\nOS fingerprinting\t\n136\np0f\t\n137\nNmap\t\n140\nSummary\t\n141\n" }, { "page_number": 17, "text": "Table of Contents\n[ iv ]\nChapter 6: Enumerating Target\t\n143\nIntroducing port scanning\t\n143\nUnderstanding the TCP/IP protocol\t\n144\nUnderstanding the TCP and UDP message format\t\n146\nThe network scanner\t\n149\nNmap\t\n150\nNmap target specification\t\n153\nNmap TCP scan options\t\n155\nNmap UDP scan options\t\n156\nNmap port specification\t\n157\nNmap output options\t\n159\nNmap timing options\t\n161\nNmap useful options\t\n162\nNmap for scanning the IPv6 target\t\n165\nThe Nmap scripting engine\t\n166\nNmap options for Firewall/IDS evasion\t\n172\nUnicornscan\t\n173\nZenmap\t\n175\nAmap\t\n179\nSMB enumeration\t\n180\nSNMP enumeration\t\n181\nonesixtyone\t\n182\nsnmpcheck\t\n183\nVPN enumeration\t\n184\nike-scan\t\n184\nSummary\t\n188\nChapter 7: Vulnerability Mapping\t\n189\nTypes of vulnerabilities\t\n190\nLocal vulnerability\t\n191\nRemote vulnerability\t\n191\nVulnerability taxonomy\t\n192\nOpen Vulnerability Assessment System (OpenVAS)\t\n193\nTools used by OpenVAS\t\n194\nCisco analysis\t\n197\nCisco auditing tool\t\n198\nCisco global exploiter\t\n199\nFuzz analysis\t\n201\nBED\t\n201\nJBroFuzz\t\n203\nSMB analysis\t\n205\nImpacket Samrdump\t\n206\n" }, { "page_number": 18, "text": "Table of Contents\n[ v ]\nSNMP analysis\t\n207\nSNMP Walk\t\n208\nWeb application analysis\t\n210\nDatabase assessment tools\t\n211\nDBPwAudit\t\n211\nSQLMap\t\n213\nSQL Ninja\t\n217\nWeb application assessment \t\n220\nBurp Suite\t\n220\nNikto2\t\n223\nParos proxy\t\n225\nW3AF\t\n226\nWafW00f\t\n228\nWebScarab\t\n229\nSummary\t\n231\nChapter 8: Social Engineering\t\n233\nModeling the human psychology\t\n234\nAttack process\t\n234\nAttack methods\t\n235\nImpersonation\t\n236\nReciprocation\t\n236\nInfluential authority\t\n237\nScarcity\t\n237\nSocial relationship\t\n238\nSocial Engineering Toolkit (SET)\t\n238\nTargeted phishing attack\t\n240\nSummary\t\n244\nChapter 9: Target Exploitation\t\n245\nVulnerability research\t\n246\nVulnerability and exploit repositories\t\n247\nAdvanced exploitation toolkit\t\n249\nMSFConsole\t\n250\nMSFCLI\t\n252\nNinja 101 drills\t\n253\nScenario 1\t\n254\nScenario 2\t\n255\nScenario 3\t\n261\nScenario 4\t\n270\nWriting exploit modules\t\n275\nSummary\t\n281\n" }, { "page_number": 19, "text": "Table of Contents\n[ vi ]\nChapter 10: Privilege Escalation\t\n283\nPrivilege escalation using a local exploit\t\n284\nPassword attack tools\t\n287\nOffline attack tools\t\n289\nhash-identifier\t\n289\nHashcat\t\n290\nRainbowCrack\t\n293\nsamdump2\t\n298\nJohn\t\n299\nJohnny\t\n303\nOphcrack\t\n304\nCrunch\t\n305\nOnline attack tools\t\n307\nCeWL\t\n308\nHydra\t\n309\nMedusa\t\n312\nNetwork spoofing tools\t\n313\nDNSChef\t\n313\nSetting up a DNS proxy\t\n313\nFaking a domain\t\n314\narpspoof\t\n315\nEttercap\t\n318\nNetwork sniffers\t\n321\ndsniff\t\n322\ntcpdump\t\n323\nWireshark\t\n323\nSummary\t\n326\nChapter 11: Maintaining Access\t\n329\nUsing operating system backdoors\t\n329\nCymothoa\t\n330\nIntersect\t\n332\nThe Meterpreter backdoor\t\n336\nWorking with tunneling tools\t\n339\ndns2tcp\t\n339\niodine\t\n341\nConfiguring the DNS server \t\n341\nRunning the iodine server\t\n342\nRunning the iodine client\t\n342\nncat\t\n342\nproxychains\t\n344\nptunnel\t\n345\nsocat\t\n346\nGetting HTTP header information\t\n349\n" }, { "page_number": 20, "text": "Table of Contents\n[ vii ]\nTransferring files\t\n349\nsslh\t\n350\nstunnel4\t\n352\nCreating web backdoors\t\n356\nWeBaCoo\t\n356\nweevely\t\n359\nPHP Meterpreter\t\n362\nSummary\t\n364\nChapter 12: Documentation and Reporting\t\n365\nDocumentation and results verification\t\n366\nTypes of reports\t\n367\nThe executive report\t\n368\nThe management report\t\n368\nThe technical report\t\n370\nNetwork penetration testing report (sample contents)\t\n371\nPreparing your presentation\t\n372\nPost-testing procedures\t\n372\nSummary\t\n374\nPART III: Extra Ammunition\nAppendix A: Supplementary Tools\t\n377\nReconnaissance tool\t\n377\nVulnerability scanner\t\n381\nNeXpose Community Edition\t\n381\nInstalling NeXpose\t\n382\nStarting the NeXpose community\t\n383\nLogging in to the NeXpose community\t\n384\nUsing the NeXpose community\t\n386\nWeb application tools\t\n389\nGolismero\t\n389\nArachni\t\n391\nBlindElephant\t\n393\nNetwork tool\t\n395\nNetcat\t\n395\nOpen connection\t\n395\nService banner grabbing\t\n396\nSimple chat server\t\n396\nFile transfer\t\n397\nPortscanning\t\n397\nBackdoor shell\t\n398\nReverse shell\t\n399\nSummary\t\n400\n" }, { "page_number": 21, "text": "Table of Contents\n[ viii ]\nAppendix B: Key Resources\t\n401\nVulnerability disclosure and tracking\t\n401\nPaid incentive programs\t\n404\nReverse engineering resources\t\n404\nPenetration testing learning resources\t\n405\nExploit development learning resources\t\n407\nPenetration testing on a vulnerable environment\t\n407\nOnline web application challenges\t\n407\nVirtual machines and ISO images\t\n408\nNetwork ports\t\n410\nIndex\t\n413\n" }, { "page_number": 22, "text": "Preface\nKali Linux is a penetration testing and security auditing platform with advanced \ntools to identify, detect, and exploit any vulnerabilities uncovered in the target \nnetwork environment. Applying an appropriate testing methodology equipped with \nwell-defined business objectives and a scheduled test plan will result in the robust \npenetration testing of your network.\nKali Linux – Assuring Security by Penetration Testing is a fully focused, structured \nbook that provides guidance on developing practical penetration testing skills by \ndemonstrating the cutting-edge hacker tools and techniques in a coherent step-by-step \nstrategy. It offers all the essential lab preparation and testing procedures to reflect real-\nworld attack scenarios from your business perspective in today's digital age.\nThis book reveals the industry's best approach for logical and systematic \npenetration testing process.\nThis book starts with lab preparation and testing procedures, explaining the basic \ninstallation and configuration setup, discussing different types of penetration \ntesting, uncovering open security testing methodologies, and proposing the Kali \nLinux specific testing process. We shall discuss a number of security assessment \ntools necessary to conduct penetration testing in their respective categories (target \nscoping, information gathering, discovery, enumeration, vulnerability mapping, \nsocial engineering, exploitation, privilege escalation, maintaining access, and \nreporting), following the formal testing methodology. Each of these tools is \nillustrated with real-world examples to highlight their practical usage and proven \nconfiguration techniques. We have also provided extra weaponry treasures and key \nresources that may be crucial to any professional penetration testers.\nThis book will serve as a single professional, practical, and expert guide to develop \nnecessary penetration testing skills from scratch. You will be trained to make the best \nuse of Kali Linux either in a real-world environment or in an experimental test bed.\n" }, { "page_number": 23, "text": "Preface\n[ 2 ]\nWhat this book covers\nChapter 1, Beginning with Kali Linux, introduces you to Kali Linux, a Live DVD Linux \ndistribution specially developed to help in the penetration testing process. You will \nlearn a brief history of Kali Linux and several categories of tools that Kali Linux has. \nNext, you will also learn how to get, use, configure, and update Kali Linux as well \nas how to configure several important network services (HTTP, MySQL, and SSH) \nin Kali Linux. You will also learn how to install and configure a vulnerable virtual \nmachine image for your testing environment and several ways that can be used to \ninstall additional tools in Kali Linux.\nChapter 2, Penetration Testing Methodology, discusses the basic concepts, rules, \npractices, methods, and procedures that constitute a defined process for a \npenetration testing program. You will learn about making a clear distinction \nbetween two well-known types of penetration testing, black box and white box. \nThe differences between vulnerability assessment and penetration testing will also \nbe analyzed. You will also learn about several security testing methodologies and \ntheir core business functions, features, and benefits. These include OSSTMM, ISSAF, \nOWASP, and WASC-TC. Thereafter, you will learn about a general penetration \nKali Linux testing process incorporated with 10 consecutive steps to conduct a \npenetration testing assignment from an ethical standpoint.\nChapter 3, Target Scoping, covers a scope process to provide necessary guidelines on \nnormalizing the test requirements. A scope process will introduce and describe each \nfactor that builds a practical roadmap towards test execution. This process integrates \nseveral key elements, such as gathering client requirements, preparing a test plan, \nprofiling test boundaries, defining business objectives, and project management and \nscheduling. You will learn to acquire and manage the information about the target's \ntest environment.\nChapter 4, Information Gathering, introduces you to the information gathering phase. \nYou will learn how to use public resources to collect information about the target \nenvironment. Next, you learn how to analyze DNS information and collect network \nrouting information. Finally, you will learn how to utilize search engines to get \ninformation of the target domain, e-mail addresses, and document metadata from \nthe target environment.\nChapter 5, Target Discovery, introduces you to the target discovery process. You will \nlearn the purpose of target discovery and the tools that can be used to identify target \nmachines. At the end of this chapter, you will also learn about the tools that can be \nused to perform OS fingerprinting on the target machines.\n" }, { "page_number": 24, "text": "Preface\n[ 3 ]\nChapter 6, Enumerating Target, introduces you to target enumeration and its purpose. \nYou will learn a brief theory on port scanning and several tools that can be used to \ndo port scanning. You will also learn about various options available to be used by \nthe Nmap port scanner tool. Also, you will learn about how to find SMB, SNMP, and \nVPN available in the target machine in the last part of the chapter.\nChapter 7, Vulnerability Mapping, discusses two generic types of vulnerabilities: local \nand remote. You will get insights on vulnerability taxonomy, pointing to industry \nstandards that can be used to classify any vulnerability according to its unifying \ncommonality pattern. Additionally, you will learn a number of security tools that \ncan assist you in finding and analyzing the security vulnerabilities present in a \ntarget environment. These include OpenVAS, Cisco, Fuzzing, SMB, SNMP, and web \napplication analysis tools.\nChapter 8, Social Engineering, covers some core principles and practices adopted \nby professional social engineers to manipulate humans into divulging information \nor performing an act. You will learn some of the basic psychological principles that \nformulate the goals and vision of a social engineer. You will also learn about the \nattack process and methods of social engineering followed by real-world examples. \nIn the end, you will be given hands-on exercise using the social engineering tools \nthat can assist you in evaluating the target's human infrastructure.\nChapter 9, Target Exploitation, highlights the practices and tools that can be used \nto conduct a real-world exploitation. The chapter will explain what areas of \nvulnerability research are crucial in order to understand, examine, and test the \nvulnerability. Additionally, it will also point out several exploit repositories that \nshould keep you informed about the publicly available exploits and when to use \nthem. You will also learn to use one of the infamous exploitation toolkits from a \ntarget evaluation perspective. Moreover, you will discover the steps for writing a \nsimple exploit module for the Metasploit framework.\nChapter 10, Privilege Escalation, introduces you to privilege escalation as well as \nnetwork sniffing and spoofing. You will learn how to escalate your gained privilege \nusing a local exploit. You will also learn the tools required to attack a password via \nthe offline or online technique. You will also learn about several tools that can be \nused to spoof the network traffic. In the last part of this chapter, you will discover \nseveral tools that can be used to do a network sniffing attack.\nChapter 11, Maintaining Access, introduces you to the operating system and web \nbackdoors. You will learn about several backdoors that are available and how to use \nthem. You will also learn about several network tunneling tools that can be used to \ncreate covert communication between the attacker and the victim machine.\n" }, { "page_number": 25, "text": "Preface\n[ 4 ]\nChapter 12, Documentation and Reporting, covers the penetration testing directives \nfor documentation, report preparation, and presentation. These directives draw a \nsystematic, structured, and consistent way to develop the test report. Furthermore, \nyou will learn about the process of results verification, types of reports, presentation \nguidelines, and the post-testing procedures.\nAppendix A, Supplementary Tools, describes several additional tools that can be used \nfor the penetration testing job.\nAppendix B, Key Resources, explains various key resources to help you become more \nskillful in the penetration testing field..\nWhat you need for this book\nAll the necessary requirements for the installation, configuration, and use of Kali \nLinux have been discussed in Chapter 1, Beginning with Kali Linux.\nWho this book is for\nIf you are an IT security professional or a network administrator who has a basic \nknowledge of Unix/Linux operating systems, including an awareness of information \nsecurity factors, and you want to use Kali Linux for penetration testing, this book is \nfor you.\nConventions\nIn this book, you will find a number of styles of text that distinguish between \ndifferent kinds of information. The following are some examples of these styles and \nan explanation of their meaning.\nCode words in text, database table names, folder names, filenames, file extensions, \npathnames, dummy URLs, user input, and Twitter handles are shown as follows: \n\"For the second example, we will use a simple program called cisco_crack.\"\nA block of code is set as follows:\n[-] Searching in Google:\n Searching 0 results...\n[+] Emails found:\n------------------\ninfo@example.com\nuser1@example.com\nuser2@example.com\nuser3@example.com\n" }, { "page_number": 26, "text": "Preface\n[ 5 ]\nWhen we wish to draw your attention to a particular part of a code block, the \nrelevant lines or items are set in bold:\n# SET TO ON IF YOU WANT TO USE EMAIL IN CONJUNCTION WITH WEB ATTACK\nWEBATTACK_EMAIL=ON\nAny command-line input or output is written as follows:\n# metagoofil -d example.com -l 20 -t doc,pdf –n 5 -f test.html -o test\nNew terms and important words are shown in bold. Words that you see on the \nscreen, in menus, or dialog boxes, for example, appear in the text as follows: \"To \naccess Maltego from the Kali Linux menu, navigate to Kali Linux | Information \nGathering | OSINT Analysis | maltego.\"\nWarnings or important notes appear in a box like this.\nTips and tricks appear like this.\nReader feedback\nFeedback from our readers is always welcome. Let us know what you think about \nthis book—what you liked or may have disliked. Reader feedback is important for us \nto develop titles that you really get the most out of.\nTo send us general feedback, simply send an e-mail to feedback@packtpub.com, \nand mention the book title via the subject of your message.\nIf there is a topic that you have expertise in and you are interested in either writing \nor contributing to a book, see our author guide on www.packtpub.com/authors.\nCustomer support\nNow that you are the proud owner of a Packt book, we have a number of things to \nhelp you to get the most from your purchase.\n" }, { "page_number": 27, "text": "Preface\n[ 6 ]\nErrata\nAlthough we have taken every care to ensure the accuracy of our content, mistakes \ndo happen. If you find a mistake in one of our books—maybe a mistake in the text or \nthe code—we would be grateful if you would report this to us. By doing so, you can \nsave other readers from frustration and help us improve subsequent versions of this \nbook. If you find any errata, please report them by visiting http://www.packtpub.\ncom/submit-errata, selecting your book, clicking on the errata submission form link, \nand entering the details of your errata. Once your errata are verified, your submission \nwill be accepted and the errata will be uploaded on our website, or added to any list of \nexisting errata, under the Errata section of that title. Any existing errata can be viewed \nby selecting your title from http://www.packtpub.com/support.\nPiracy\nPiracy of copyright material on the Internet is an ongoing problem across all media. \nAt Packt, we take the protection of our copyright and licenses very seriously. If you \ncome across any illegal copies of our works, in any form, on the Internet, please \nprovide us with the location address or website name immediately so that we can \npursue a remedy.\nPlease contact us at copyright@packtpub.com with a link to the suspected \npirated material.\nWe appreciate your help in protecting our authors, and our ability to bring you \nvaluable content.\nQuestions\nYou can contact us at questions@packtpub.com if you are having a problem with \nany aspect of the book, and we will do our best to address it.\n" }, { "page_number": 28, "text": "PART I\nLab Preparation \nand Testing \nProcedures\nBeginning with Kali Linux\nPenetration Testing Methodology \n" }, { "page_number": 29, "text": "" }, { "page_number": 30, "text": "Beginning with Kali Linux\nThis chapter will guide you through the wonderful world of Kali Linux—a \nspecialized Linux distribution for the purpose of penetration testing. In this chapter, \nwe will cover the following topics:\n•\t\nA brief history of Kali\n•\t\nSeveral common usages of Kali\n•\t\nDownloading and installing Kali\n•\t\nConfiguring and updating Kali\nAt the end of this chapter, we will describe how to install additional weapons and \nhow to configure Kali Linux.\nA brief history of Kali Linux\nKali Linux (Kali) is a Linux distribution system that was developed with a focus on \nthe penetration testing task. Previously, Kali Linux was known as BackTrack, which \nitself is a merger between three different live Linux penetration testing distributions: \nIWHAX, WHOPPIX, and Auditor. \nBackTrack is one of the most famous Linux distribution systems, as can be proven by \nthe number of downloads that reached more than four million as of BackTrack Linux \n4.0 pre final.\nKali Linux Version 1.0 was released on March 12, 2013. Five days later, Version 1.0.1 \nwas released, which fixed the USB keyboard issue. In those five days, Kali has been \ndownloaded more than 90,000 times.\n" }, { "page_number": 31, "text": "Beginning with Kali Linux\n[ 10 ]\nThe following are the major features of Kali Linux (http://docs.kali.org/\nintroduction/what-is-kali-linux):\n•\t\nIt is based on the Debian Linux distribution\n•\t\nIt has more than 300 penetration testing applications\n•\t\nIt has vast wireless card support\n•\t\nIt has a custom kernel patched for packet injection\n•\t\nAll Kali software packages are GPG signed by each developer\n•\t\nUsers can customize Kali Linux to suit their needs\n•\t\nIt supports ARM-based systems\nKali Linux tool categories\nKali Linux contains a number of tools that can be used during the penetration testing \nprocess. The penetration testing tools included in Kali Linux can be categorized into \nthe following categories:\n•\t\nInformation gathering: This category contains several tools that can be \nused to gather information about DNS, IDS/IPS, network scanning, \noperating systems, routing, SSL, SMB, VPN, voice over IP, SNMP, e-mail \naddresses, and VPN. \n•\t\nVulnerability assessment: In this category, you can find tools to scan \nvulnerabilities in general. It also contains tools to assess the Cisco network, \nand tools to assess vulnerability in several database servers. This category \nalso includes several fuzzing tools.\n•\t\nWeb applications: This category contains tools related to web applications \nsuch as the content management system scanner, database exploitation, \nweb application fuzzers, web application proxies, web crawlers, and web \nvulnerability scanners.\n•\t\nPassword attacks: In this category, you will find several tools that can be \nused to perform password attacks, online or offline. \n•\t\nExploitation tools: This category contains tools that can be used to exploit \nthe vulnerabilities found in the target environment. You can find exploitation \ntools for the network, Web, and database. There are also tools to perform \nsocial engineering attacks and find out about the exploit information.\n•\t\nSniffing and spoofing: Tools in this category can be used to sniff the network \nand web traffic. This category also includes network spoofing tools such as \nEttercap and Yersinia.\n" }, { "page_number": 32, "text": "Chapter 1\n[ 11 ]\n•\t\nMaintaining access: Tools in this category will be able to help you maintain \naccess to the target machine. You might need to get the highest privilege \nlevel in the machine before you can install tools in this category. Here, you \ncan find tools for backdooring the operating system and web application. \nYou can also find tools for tunneling.\n•\t\nReporting tools: In this category, you will find tools that help you document \nthe penetration-testing process and results.\n•\t\nSystem services: This category contains several services that can be useful \nduring the penetration testing task, such as the Apache service, MySQL \nservice, SSH service, and Metasploit service.\nTo ease the life of a penetration tester, Kali Linux has provided us with a category \ncalled Top 10 Security Tools. Based on its name, these are the top 10 security \ntools commonly used by penetration testers. The tools included in this category \nare aircrack-ng, burp-suite, hydra, john, maltego, metasploit, nmap, sqlmap, \nwireshark, and zaproxy.\nBesides containing tools that can be used for the penetration testing task, Kali Linux \nalso comes with several tools that you can use for the following:\n•\t\nWireless attacks: This category includes tools to attack Bluetooth, RFID/\nNFC, and wireless devices.\n•\t\nReverse engineering: This category contains tools that can be used to debug \na program or disassemble an executable file.\n•\t\nStress testing: This category contains tools that can be used to help you in \nstress testing your network, wireless, Web, and VOIP environment.\n•\t\nHardware hacking: Tools in this category can be used if you want to work \nwith Android and Arduino applications.\n•\t\nForensics: In this category, you will find several tools that can be used for \ndigital forensics, such as acquiring a hard disk image, carving files, and \nanalyzing the hard disk image. To use the forensics capabilities in Kali Linux \nproperly, you need to navigate to Kali Linux Forensics | No Drives or Swap \nMount in the booting menu. With this option, Kali Linux will not mount the \ndrives automatically, so it will preserve the drives' integrity. \nIn this book, we are focusing only on Kali Linux's penetration testing tools.\n" }, { "page_number": 33, "text": "Beginning with Kali Linux\n[ 12 ]\nDownloading Kali Linux\nThe first thing to do before installing and using Kali Linux is to download it. You can \nget Kali Linux from the Kali Linux website (http://www.kali.org/downloads/).\nOn the download page, you can select the official Kali Linux image based on the \nfollowing items, which is also shown in the next screenshot:\n•\t\nMachine architecture: i386, amd64, armel, and armhf\n•\t\nImage type: ISO image or VMware image\nIf you want to burn the image to a DVD or install Kali Linux to your machine, you \nmight want to download the ISO image version. However, if you want to use Kali \nLinux for VMWare, you can use the VMWare image file to speed up the installation \nand configuration for a virtual environment.\nAfter you have downloaded the image file successfully, you need to compare the \nSHA1 hash value from the downloaded image with the SHA1 hash value provided \non the download page. The purpose of checking the SHA1 value is to ensure the \nintegrity of the downloaded image is preserved. This prevents the user from either \ninstalling a corrupt image or an image file that has been maliciously tampered with.\n" }, { "page_number": 34, "text": "Chapter 1\n[ 13 ]\nIn the UNIX/Linux/BSD operating system, you can use the sha1sum command to \ncheck the SHA1 hash value of the downloaded image file. Remember that it might \ntake some time to compute the hash value of the Kali Linux image file due to its size. \nFor example, to generate the hash value of the kali-linux-1.0.1-i386.iso file, the \nfollowing command is used:\nsha1sum kali-linux-1.0.1-i386.iso\n41e5050f8709e6cd6a7d1baaa3ee2e89f8dfae83 kali-linux-1.0.1-i386.iso\nIn the Windows world, there are many tools that can be used to generate the SHA1 \nhash value; one of them is sha1sum. It is available from http://www.ring.gr.jp/\npub/net/gnupg/binary/sha1sum.exe. \nWe like it because of its small size and it just works. If you want an alternative tool \ninstead of sha1sum, there is HashMyFiles (http://www.nirsoft.net/utils/hash_\nmy_files.html). HashMyFiles supports MD5, SHA1, CRC32, SHA-256, SHA-384, \nand SHA-512 hash algorithms.\nAfter you have downloaded HashMyFiles, just run the HashMyFiles and select the \nfile by navigating to File | Add Files to find out the SHA1 hash value of a file. Or, \nyou can press F2 to perform the same function. Then, choose the image file you want.\nThe following screenshot resembles the SHA1 hash value generated by HashMyFiles \nfor the Kali Linux i386 ISO image file:\n" }, { "page_number": 35, "text": "Beginning with Kali Linux\n[ 14 ]\nYou need to compare the SHA1 hash value generated by sha1sum, HashMyFiles \nor other similar tools with the SHA1 hash value displayed on the Kali Linux \ndownload page.\nIf both the values match, you can go straight to the Using Kali Linux section. But \nif they do not match, it means that your image file is broken; you may want to \ndownload the file again from an official download mirror. For this case, we can see \nthat the SHA1 hash values match.\nUsing Kali Linux\nYou can use Kali Linux in one of the following ways:\n•\t\nYou can run Kali Linux directly from the Live DVD\n•\t\nYou can install Kali Linux on the hard disk and then run it\n•\t\nYou can install Kali Linux on the USB disk (as a portable Kali Linux)\nIn the following sections, we will briefly describe each of those methods.\nRunning Kali using Live DVD\nIf you want to use Kali Linux without installing it first, you can do so by burning the \nISO image file to a DVD. After the burn process finishes successfully, boot up your \nmachine with that DVD. You need to make sure that you have set the machine to \nboot from the DVD. \nThe advantage of using Kali Linux as a Live DVD is that it is very fast to set up and \nis very easy to use.\nUnfortunately, the Live DVD has several drawbacks; for example, any files or \nconfiguration changes will not be saved after the reboot. Additionally, running Kali \nLinux from the DVD is slow as compared to running Kali Linux from the hard disk \nbecause the DVD's reading speed is slower than the hard disk's reading speed.\nThis method of running Kali is recommended only if you just want to test Kali. \nHowever, if you want to work with Kali Linux extensively, we suggest that you \ninstall Kali Linux.\n" }, { "page_number": 36, "text": "Chapter 1\n[ 15 ]\nInstalling on a hard disk\nTo install Kali Linux on your hard disk, you can choose one of the following methods:\n•\t\nInstallation on a physical/real machine (regular installation)\n•\t\nInstallation on a virtual machine\nYou can choose whichever method is suitable for you, but we personally prefer to \ninstall Kali Linux on a virtual machine.\nInstalling Kali on a physical machine\nBefore you install Kali Linux on a physical/real machine, make sure that you install \nit on an empty hard drive. If your hard drive already has some data on it, that data \nwill be lost during the installation process because the installer will format the hard \ndrive. For easy installation, we suggest that you use all of the available space in the \nhard disk. If your machine contains another operating system, you need to create a \nseparate disk partition for Kali Linux. Be careful while doing this or you could end \nup corrupting your operating system.\nThe official Kali Linux documentation that describes how to \ninstall Kali Linux with the Windows operating system can be \nfound at http://docs.kali.org/installation/dual-\nboot-kali-with-windows.\nThere are several tools that can be used to help you perform disk partitioning. In the \nopen source area, the following Linux Live CDs are available:\n•\t\nSystemRescueCD (http://www.sysresccd.org/) \n•\t\nGParted Live (http://gparted.sourceforge.net/livecd.php) \n•\t\nKali Linux (http://www.kali.org)\nTo use the Linux Live CD, you just need to boot it up and you are ready for disk \npartitioning. Make sure that you back up your data before you use the Linux Live \nCD disk partitioning tool. Even though they are safe for use in our experience, there \nis nothing wrong with being cautious, especially if you have important data on the \nhard disk.\n" }, { "page_number": 37, "text": "Beginning with Kali Linux\n[ 16 ]\nAfter you are done with the disk partitioning or you just want to use all the hard \ndisk space, you can boot your machine using the Kali Linux Live DVD and select \nthe Install or Graphical install option when you are prompted with the Kali Linux \nLive CD menu:\nAfter that, you will see an installation window. You need to set up several things \nduring the installation process:\n1.\t First, you need to set the installation language. The default language used \nis English.\n2.\t Select the country you live in using the drop-down box.\n3.\t Next, set the locale setting. The default value is United States – en_\nUS.UTF-8.\n4.\t The keymap value comes next. You can use the suggested keymap value \n(American English) if don't have a specific keyboard layout.\n5.\t Next, you will be asked to configure the network, starting with setting the \nhostname. Then, you are asked to fill in the domain name.\n6.\t Later on, you will need to set the root password.\n7.\t The installer then asks you to select your time zone.\n" }, { "page_number": 38, "text": "Chapter 1\n[ 17 ]\n8.\t In the disk partitioning segment, the installer will guide you through the disk \npartitioning process. If you use an empty hard disk, just select the default \nGuided - use entire disk option for better ease. If you have some other \noperating system installed on your machine, you might first want to create a \nseparate partition for Kali Linux and then select Manual in this menu. After \nyou have selected the suitable menu, the installer will create the partition.\n9.\t The installer will ask you about the partitioning scheme; the default scheme \nis All files in one partition. Remember that if you want to store files in the \nhome directory, you should select Separate /home partition so that those \nfiles won't be deleted if you reinstall the system. The /home partition's \nsize really depends on your needs. If you want to put all your data in that \ndirectory, you may want a big partition size (more than 50 GB). For average \nusage, you can go ahead with 10 to 20 GB.\n10.\t The installer will display an overview of your currently configured \npartitions, as shown in the following screenshot:\n11.\t Next, the installer will install the Kali Linux system. The installation will \nbe completed in several minutes and you will have Kali Linux installed on \nyour hard disk afterwards. In our test machine, the installation took around \n20 minutes.\n12.\t After the installation is finished, the installer will ask you to configure the \npackage manager. Next, it will ask you to install GRUB to the Master Boot \nRecord. You can just choose the default values for these two questions. \nBeware if you have some other operating system on the same machine, you \nshould not choose to install GRUB to the Master Boot Record.\n" }, { "page_number": 39, "text": "Beginning with Kali Linux\n[ 18 ]\n13.\t If you see the following message, it means that your Kali installation \nis complete:\n14.\t You can restart the machine to test your new Kali installation by \nselecting the Continue button. After restarting, you will see the \nfollowing Kali login screen:\n15.\t You can log in using the credentials that you configured in the \ninstallation process.\n" }, { "page_number": 40, "text": "Chapter 1\n[ 19 ]\nInstalling Kali on a virtual machine\nYou can also install Kali Linux to a virtual machine environment as a guest operating \nsystem. The advantages of this type of installation are that you do not need to \nprepare a separate physical hard disk partition for the Kali Linux image and can use \nyour existing operating system as is. \nWe will use VirtualBox (http://www.virtualbox.org) \nas the virtual machine software. VirtualBox is an open source \nvirtualization software that is available for Windows, Linux, OS \nX, and Solaris operating systems.\nUnfortunately, there is also a disadvantage of running Kali Linux on a virtual \nmachine; it is slower as compared to running Kali Linux on a physical machine. \nThere are two options that can be utilized for installing Kali Linux on a virtual \nmachine. The first option is to install the Kali Linux ISO image into a virtual machine. \nThis option will take more time compared to the VMware image installation. The \nadvantage of this method is that you can customize your Kali installation.\nInstalling Kali on a virtual machine from the ISO image\nTo install a Kali Linux ISO image on a virtual machine, the following steps can \nbe used:\n1.\t Create a new virtual machine by selecting New from the VirtualBox \ntoolbar menu.\n2.\t After that, you need to define the virtual machine's name and the operating \nsystem's type. Here, we set the VM's name to Kali Linux and we choose \nLinux for the OS type and Debian for the version:\n" }, { "page_number": 41, "text": "Beginning with Kali Linux\n[ 20 ]\n3.\t Then, you need to define the VM's base memory size. The more memory you \nprovide, the better the virtual machine will be. Here, we allocated 2048 MB \nof memory to the Kali Linux virtual machine. Remember that you can't give \nall of your physical memory to the VM because you still need the memory to \nrun your host operating system:\n4.\t Next, you will be asked to create a virtual hard disk. You can just select the \nVDI as the hard disk type along with a dynamically allocated virtual disk file. \nWe suggest creating at least a 32 GB virtual hard disk. If you want to install \nsome software packages later on, you may want to create a larger virtual \nhard disk:\n" }, { "page_number": 42, "text": "Chapter 1\n[ 21 ]\n5.\t After this, your newly created VM will be listed on the VirtualBox menu. \n6.\t To use the Kali Linux ISO image, select the VM from the VirtualBox menu \nand then click on the Storage menu to configure it:\n7.\t From Storage Tree, select IDE Controller and in the Attributes, select Kali \nLinux ISO image file; in this case the filename for the CD/DVD drive is \nkali-linux-1.0.1-i386.iso. If successful, you will see the ISO image \nname in the Controller: IDE field:\n8.\t To install the Kali Linux ISO image, just run your new virtual machine. You \ncan refer to the Installing Kali on a physical machine section for guidance on \nhow to install Kali Linux.\n" }, { "page_number": 43, "text": "Beginning with Kali Linux\n[ 22 ]\nInstalling Kali in a virtual machine using the provided Kali \nVM image\nThe second option is using the VMWare image provided by Kali Linux. \nThe Kali Linux team only provides Kali Linux GNOME \nVMware image for an i386 machine.\nWith this option, you can install Kali Linux on a virtual machine with ease. \nAfter downloading the Kali Linux VMware image (kali-linux-1.0-i386-gnome-\nvm.tar.gz), you need to verify the SHA1 hash of the downloaded file with the hash \nvalue provided in the download page. If the hash value is the same, you can extract \nthe image file to the appropriate folder. \nAs the VMware image is compressed in the GZ format, you can use any software \nthat can extract a .gz file such as gzip or 7-Zip if you use a Windows operating \nsystem. If you have extracted it successfully, you will find 21 files in the directory:\nTo create the new virtual machine using this VM image file, select New from the \nVirtualBox icon toolbar. Next, you will need to answer the following questions:\n1.\t We use kali-gnome-vm-32 as the VM name and choose Linux as the \noperating system and Debian as the version.\n2.\t We configure the Kali Linux virtual machine to use 2048 MB as its \nmemory size.\n" }, { "page_number": 44, "text": "Chapter 1\n[ 23 ]\n3.\t Next, we define the virtual hard disk to Use an existing virtual hard drive \nfile. Then, we select the kali-linux-i386-gnome-vm.vmdk file for the hard \ndisk. After that, we choose Create to create the virtual machine, as shown in \nthe following screenshot:\nThe following is the default configuration of the Kali Linux \nVMware image:\n•\t\nHard disk size: 30 GB\n•\t\nNetwork type: NAT\n•\t\nUsername: root\n•\t\nPassword: toor\nFor penetration purposes, we should avoid using NAT as the network \ntype. The recommended network type is bridged.\nChange the default password for Kali when you configure the \nKali VM. \n" }, { "page_number": 45, "text": "Beginning with Kali Linux\n[ 24 ]\nIf successful, you will see the new virtual machine in the virtual manager list:\nTo run the Kali Linux virtual machine, click on the Start icon at the top of the \nVirtualBox menu bar. After the boot process, Kali Linux will display its login prompt.\nIf you got the following error message, you need to install the VirtualBox Extension \nPack. You can get it from http://www.virtualbox.org/wiki/Downloads.\nRemember to download the VirtualBox Extension Pack with \nthe same version as the VirtualBox. For example, if you use \nVirtualBox Version 4.3.0, you should use the Extension Pack \nVersion 4.3.0 too.\n" }, { "page_number": 46, "text": "Chapter 1\n[ 25 ]\nTo install the extension pack from the VirtualBox Manager, perform the \nfollowing steps:\n1.\t Navigate to File | Preferences; it will then display the Settings window. \nNext, select the Extensions menu:\n2.\t Click on the Add package button to select the VirtualBox Extension Pack. \nVirtualBox will then display a pop-up window that will ask you to review \nthe description and then proceed:\n" }, { "page_number": 47, "text": "Beginning with Kali Linux\n[ 26 ]\n3.\t Select Install to install the extension pack and follow the given instructions. \nIf the installation is successful, you will see the extension pack in the list:\n4.\t You can then log in to Kali Linux using the default username and password.\nInstalling Kali on a USB disk\nThe third option to use Kali Linux is by installing it to a USB flash disk; we call this \nmethod Portable Kali Linux. According to the official Kali documentation, this \nis the Kali developers' favorite and fastest method of booting and installing Kali. \nCompared to the hard disk installation, you can run Kali Linux using any computer \nthat supports booting from the USB flash disk with this method.\nThe installation procedure for the USB flash disk is also applicable to \nthe installation of memory cards (SSD, SDHC, SDXC, and so on).\nThere are several tools available to create portable Kali Linux. One of them is \nRufus (http://rufus.akeo.ie/). This tool can be run only from a Windows \noperating system.\nYou can use other tools to create a bootable disk from the ISO image, such as:\n•\t\nWin32DiskImager (https://launchpad.net/win32-image-writer) \n•\t\nUniversal USB Installer (http://www.pendrivelinux.com/universal-\nusb-installer-easy-as-1-2-3/)\n•\t\nLinux Live USB Creator (http://www.linuxliveusb.com)\nBefore creating portable Kali Linux, you need to prepare a couple of things:\n•\t\nKali Linux ISO image: Even though you can use the portable creator tool to \ndownload the image directly while making the Kali Linux portable, we think \nit's much better to download the ISO first and then configure Rufus to use the \nimage file.\n" }, { "page_number": 48, "text": "Chapter 1\n[ 27 ]\n•\t\nUSB flash disk: You need an empty USB flash disk with enough space on it. \nWe suggest using a USB flash disk with a minimum size of 16 GB.\nAfter downloading Rufus, you can run it on your Windows computer by double-\nclicking on the rufus.exe file. You will then see the Rufus window.\nIf you use a UNIX-based operating system, you can create the image \nusing the dd command. The following is an example of imaging:\ndd if=kali-linux-1.0.1-i386.iso of=/dev/sdb bs=512k\nHere, /dev/sdb is your USB flash disk.\nTo create a bootable Kali USB flash disk, we need to fill in the following options:\n•\t\nFor Device, we choose the location of the USB flash disk. In my case, it is the \nE drive in my Windows system.\n•\t\nFor Partition scheme and target system type, set it to MBR partition scheme \nfor BIOS or UEFI computers.\n•\t\nIn the Create a bootable disk using option, set the value to ISO image and \nselect the ISO image using the disk icon:\n" }, { "page_number": 49, "text": "Beginning with Kali Linux\n[ 28 ]\nClick on Start to create the bootable image:\nAfter the process is complete, save all your work first and then reboot your system \nif you want to try the USB flash disk right away. You may want to configure your \nBasic Input Output System (BIOS) to boot it from the USB disk. If there is no error, \nyou can boot up the Kali Linux from the USB flash disk.\nIf you want to add persistence capabilities to the USB flash disk, you \ncan follow the steps described in the documentation section Adding \nPersistence to Your Kali Live USB located at http://docs.kali.\norg/installation/kali-linux-live-usb-install.\nConfiguring the virtual machine\nAfter logging in to the Kali Linux virtual machine, we are going to configure several \nthings. These are important steps if we want to perform penetration testing.\nVirtualBox guest additions\nWe recommend that after you have successfully created the Kali Linux Virtual \nMachine using VirtualBox, you install VirtualBox guest additions. This add-on will \nprovide you with the following additional features:\n•\t\nIt will enable the virtual machine to be viewed in full screen\n•\t\nIt will make the mouse move faster in the virtual machine\n•\t\nIt will enable you to copy and paste the text between the host and \nguest machine\n•\t\nIt will enable the guest and host machine to share folders\n" }, { "page_number": 50, "text": "Chapter 1\n[ 29 ]\nTo install the guest additions, you can perform the following steps:\n1.\t From the VirtualBox menu, navigate to Devices | Install Guest Additions. \nYou will then see that the VirtualBox guest addition file is mounted as \na disk:\n2.\t Then, VirtualBox will display the following message. Click on Cancel to close \nthe window:\n3.\t Open the terminal console and change the VirtualBox guest additions \nCDROM mount point (/media/cdrom0):\n" }, { "page_number": 51, "text": "Beginning with Kali Linux\n[ 30 ]\n4.\t Execute VBoxLinuxAdditions.run to run the VirtualBox guest \nadditions installer:\nsh ./VBoxLinuxAdditions.run\n5.\t You may need to wait for several minutes until all of the required modules \nare successfully built and installed:\n6.\t Change to the root home directory.\n7.\t Eject the VBoxAdditions CD Image by right-clicking on the icon and selecting \nEject from the menu. If successful, the VBoxAdditions icon will disappear \nfrom the desktop.\n8.\t Reboot the virtual machine by typing the reboot command in the \nterminal console.\n9.\t After the reboot, you can switch to full screen (View | Switch to fullscreen) \nfrom the VirtualBox menu.\nSetting up networking \nIn the following section, we will discuss how to set up the networking in Kali Linux \nfor the wired and wireless network.\n" }, { "page_number": 52, "text": "Chapter 1\n[ 31 ]\nSetting up a wired connection\nIn the default Kali Linux VMware image or ISO configuration, Kali Linux uses NAT \n(Network Address Translation) as the network's connection type. In this connection \nmode, the Kali Linux machine will be able to connect to the outside world through \nthe host operating system whereas the outside world, including the host operating \nsystem, will not be able to connect to the Kali Linux virtual machine.\nFor the penetration testing task, you might need to change this networking method \nto Bridged Adapter. The following are the steps to change it:\n1.\t First, make sure you have already powered off the virtual machine. \n2.\t Then, open up the VirtualBox Manager, select the appropriate virtual \nmachine—in this case we are using the Kali Linux virtual machine—and then \nclick on the Network icon on the right-hand side and change the Attached \nto drop-down box from NAT to Bridged Adapter in Adapter 1. In the Name \nfield, you can select the network interface that is connected to the network \nyou want to test, as shown in the following screenshot:\nTo be able to use the bridge network connection, the host machine needs to \nconnect to a network device that can give you an IP address via DHCP, such as \na router or a switch.\nAs you may be aware, a DHCP IP address is not a permanent IP address; it's just a \nlease IP address. After several times (as defined in the DHCP lease time), the Kali \nLinux virtual machine will need to get a lease IP address again. This IP address \nmight be the same as the previous one or might be a different one.\nIf you want to make the IP address permanent, you can do so by saving the IP \naddress in the /etc/network/interfaces file.\nThe following is the default content of this file in Kali Linux:\nauto lo\niface lo inet loopback\n" }, { "page_number": 53, "text": "Beginning with Kali Linux\n[ 32 ]\nIn the default configuration, all of the network cards are set to use DHCP to get the \nIP address. To make a network card bind to an IP address permanently, we have to \nedit that file and change the content to the following:\nauto eth0\niface eth0 inet static\naddress 10.0.2.15\nnetmask 255.255.255.0\nnetwork 10.0.2.0\nbroadcast 10.0.2.255\ngateway 10.0.2.2\nHere, we set the first network card (eth0) to bind to the IP address of 10.0.2.15. \nYou may need to adjust this configuration according to the network environment \nyou want to test.\nSetting up a wireless connection\nBy running Kali Linux as a virtual machine, you cannot use the wireless card that \nis embedded in your laptop. Fortunately, you can use an external USB-based \nwireless card. \nTo activate your USB-based wireless card in the Kali virtual machine, plug in the \nwireless card to a USB port, navigate to Devices | USB Devices, and select your \nwireless card from the VirtualBox menu:\nIn this screenshot, we select the wireless card that uses the Realtek chipset.\nIf your USB wireless card has been successfully recognized by Kali, you can use the \ndmesg program to see the wireless card's information.\nIn the top-right section of the Kali menu, you will see the Network Connections icon. \nYou can click on it to display your network information.\n" }, { "page_number": 54, "text": "Chapter 1\n[ 33 ]\nYou will see several networks' names, wired or wireless, available for your machine:\nTo connect to the wireless network, just select the particular SSID you want by \ndouble-clicking on its name. If the wireless network requires authentication, you will \nbe prompted to enter the password. Only after you give the correct password are \nyou allowed to connect to that wireless network.\nStarting the network service\nTo control the networking process' startup or shutdown process, you can use a \nhelper script called service.\nTo start a networking service, just give the following command:\nservice networking start\nTo stop a networking service, type the following command:\nservice networking stop\nTo issue these commands, you need the root privilege.\n" }, { "page_number": 55, "text": "Beginning with Kali Linux\n[ 34 ]\nYou can test whether your network is working correctly by sending an ARP ping \nrequest to a host in the same network segment using the arping command. \nYou may find that after you reboot your Kali Linux machine, the networking service \nneeds to be started again. To make the networking service start automatically after \nthe reboot, you need to give the following command:\nupdate-rc.d networking defaults\nThis command will insert the necessary links to the /etc/rc*.d directories to start \nthe networking script automatically after Kali has been rebooted.\nConfiguring shared folders\nDuring a penetration testing process, we may find that we need to share files \nbetween the host OS and the guest OS, such as to store penetration testing results on \nthe host machine. One of the mechanisms that can be used for this requirement is to \nuse VirtualBox's Shared Folders.\nTo configure the shared folder from the VirtualBox menu, you need to power off \nthe virtual machine that you want to configure. After that, you need to select the \nappropriate guest machine's name and click on the Shared Folders menu in the \nwindow on the left. You will then see the following screen:\n" }, { "page_number": 56, "text": "Chapter 1\n[ 35 ]\nTo add the folder from the host OS, click on the + icon on the right-hand side. After \nthat, select the appropriate folder that you want to share in the host OS. The selected \nfolder path will be displayed in the Folder Path field.\nFor the Folder Name field, you can choose a name that is suitable for the folder. This \nname will be used by the guest OS to identify the host OS' shared folder.\nIf you do not want the guest OS to write to the specified shared folder, you can \ncheck the option to Read-only. If the Auto-mount option is checked, the guest OS \nwill try to mount the folder automatically after its startup, as shown in the \nfollowing screenshot:\nIn the preceding screenshot, we shared a D:\\software folder to the guest OS as a \nread-only folder. \nThe shared folder can be accessed from the virtual machine as a /media/sf_\nsoftware directory.\nSaving the guest machine state\nIf you have correctly configured your guest OS, we suggest that you save your OS \nstate. The purpose of this action is that in case you mess up your virtual machine \nbadly, you can still restore it to the previous good state.\n" }, { "page_number": 57, "text": "Beginning with Kali Linux\n[ 36 ]\nTo save the virtual machine's state, VirtualBox has provided you with this capability \nunder the menu of Machine – Take Snapshot. You need to start the virtual machine \nbefore you can take its snapshot:\nFor the Snapshot Name, you can use any name but we suggest that you put in the \ninformation about the date. You can give detailed information in the Snapshot \nDescription field. After you fill in all the information, VirtualBox will store the \nvirtual machine state; this process will take some time depending on how much \ninformation is available to be saved. \nExporting a virtual machine\nThere are times when you need to back up your virtual machine to a file or share \nyour virtual machine with other people. VirtualBox allows you to do that easily. For \nthis action, you need to turn off the virtual machine that you want to export, and \nthen navigate to File | Export Appliance.\nThe following steps will help you export an appliance:\n1.\t Select the Export Appliance menu; VirtualBox will display an Appliance \nExport Wizard screen. \n2.\t Next, choose the virtual machine that you want to export.\n3.\t Later on, you will be asked for the output file's location. By default, the \nlocation will be your directory and the file format will be ova (Open \nVirtualization Format Archive). We suggest that you use the default file \nformat if you don't know which file format to choose.\n" }, { "page_number": 58, "text": "Chapter 1\n[ 37 ]\n4.\t Next, you are prompted for the appliance export's configuration values. You \ncan configure the properties here. However, you can usually just leave them \nempty unless you need to set specific values:\nAfter this, the exporting process will take place. The time required to finish the \nexport depends on the size of the virtual machine. The bigger the virtual machine \nsize, the longer the exporting time. On my system, it took around 20 minutes to \nexport the Kali Linux virtual machine.\nUpdating Kali Linux\nKali Linux consists of hundreds of pieces of application software and an operating \nsystem kernel. You may need to update the software if you want to get the \nlatest features.\nWe suggest that you only update the software and kernel from the Kali Linux \nsoftware package repository.\nThe first thing to do after you have successfully installed and configured Kali Linux \nis to update it. As Kali is based on Debian, you can use the Debian command (apt-\nget) for the updating process.\nThe apt-get command will consult the /etc/apt/sources.list file to get \nthe update servers. You need to make sure that you have put the correct servers \nin that file.\n" }, { "page_number": 59, "text": "Beginning with Kali Linux\n[ 38 ]\nThe default sources.list file included in Kali Linux contains the following entries:\n# deb cdrom:[Debian GNU/Linux 7.0 _Kali_ - Official Snapshot i386 \nLIVE/INSTALL Binary 20130315-11:39]/ kali contrib main non-free\n#deb cdrom:[Debian GNU/Linux 7.0 _Kali_ - Official Snapshot i386 LIVE/\nINSTALL Binary 20130315-11:39]/ kali contrib main non-free\ndeb http://http.kali.org/kali kali main non-free contrib\ndeb-src http://http.kali.org/kali kali main non-free contrib\n## Security updates\ndeb http://security.kali.org/kali-security kali/updates main contrib \nnon-free\nYou need to synchronize the package's index files from the repository specified in \nthe /etc/apt/sources.list file before you can perform the update process. The \nfollowing is the command for this synchronization:\napt-get update\nMake sure that you always run apt-get update before performing a software \nupdate or installation in Kali.\nAfter the package index has been synchronized, you can perform software updates. \nThere are two command options that are available to perform an upgrade:\n•\t\napt-get upgrade: This command will upgrade all of the packages that are \ncurrently installed on the machine to the latest version. If there is a problem \nin upgrading a package, that package will be left intact in the current version.\n•\t\napt-get dist-upgrade: This command will upgrade the entire Kali Linux \ndistribution; for example, if you want to upgrade from Kali Linux 1.0.1 to \nKali Linux 1.0.2, you can use this command. This command will upgrade all \nof the packages that are currently installed and will also handle any conflicts \nduring the upgrade process; however, some specific action may be required \nto perform the upgrade.\nAfter you choose the appropriate command option to update Kali Linux, the apt-\nget program will list all of the packages that will be installed, upgraded, or removed. \nThe apt-get command will then wait for your confirmation.\nIf you have given the confirmation, the upgrade process will start. Beware, the \nupgrade process might take a long time to finish depending on your Internet \nconnection speed.\n" }, { "page_number": 60, "text": "Chapter 1\n[ 39 ]\nNetwork services in Kali Linux\nThere are several network services available in Kali Linux; in this section, we will \ndescribe only some of them: the HTTP, MySQL, and SSH service. You can find the \nother services by navigating to Kali Linux | System Services.\nHTTP\nIn your penetration testing works, you may want to have a web server for various \nreasons, such as to serve malicious web application scripts. In Kali Linux, there is \nalready an Apache web server installed; you just need to start the service.\nThe following are the steps that are required to activate your HTTP server in \nKali Linux:\n1.\t To start the Apache HTTP service from the graphical menu, navigate to Kali \nLinux | System Services | HTTPD | apache2 start; or, from the command \nline, type the following command to start the Apache server:\nservice apache2 start\n2.\t If there are no errors, the system will reply with the following message:\n[....] Starting web server: apache2 ok\n3.\t After this, you can browse to the web page; it will display the It works! page \nby default:\nTo stop the Apache HTTP service, perform the following steps:\n1.\t From the menu, navigate to Kali Linux | System Services | HTTPD | \napache2 stop; or, from the command line, type the following command to \nstart the Apache server:\nservice apache2 stop\n" }, { "page_number": 61, "text": "Beginning with Kali Linux\n[ 40 ]\n2.\t If there are no errors, the system will reply with the following message:\n[....] Stopping web server: apache2 [ ok waiting .\n3.\t Remember that the previous command will not survive the boot up. After the \nboot up, you need to give the command again. Fortunately, there is a way to \nstart the Apache HTTP service automatically after the Kali Linux boots up by \ngiving the following command:\nupdate-rc.d apache2 defaults\nThe command will add the apache2 service to be started on boot up.\nMySQL\nThe second service that we will discuss is MySQL. It is one of the relational database \nsystems. MySQL is often used with the PHP programming language and Apache \nweb server to create a dynamic, web-based application. For the penetration testing \nprocess, you can use MySQL to store your penetration testing results; for example, \nthe vulnerability information and network mapping result. Of course, you need to \nuse the application to store those results.\nTo start the MySQL service in Kali Linux, you can perform the following steps:\n1.\t In the graphical menu, navigate to Kali Linux | System Services | MySQL \n| mysql start; or, from the command line, type the following:\nservice mysql start\n2.\t Then, the system will respond with the following message:\n[ ok ] Starting MySQL database server: mysqld . . ..\n[info] Checking for tables which need an upgrade, are corrupt or \nwere not closed cleanly..\n3.\t To test whether your MySQL has already started, you can use the MySQL \nclient to connect to the server. We define the username (root) and the \npassword to log in to the MySQL server:\nmysql -u root –p\n4.\t The system will respond with the following:\nEnter password: \nWelcome to the MySQL monitor. Commands end with ; or \\g.\nYour MySQL connection id is 42\nServer version: 5.5.30-1 (Debian)\n" }, { "page_number": 62, "text": "Chapter 1\n[ 41 ]\nCopyright (c) 2000, 2013, Oracle and/or its affiliates. All rights \nreserved.\nOracle is a registered trademark of Oracle Corporation and/or its\naffiliates. Other names may be trademarks of their respective\nowners.\nType ''help;'' or ''\\h'' for help. Type ''\\c'' to clear the \ncurrent input statement.\nmysql>\n5.\t After this MySQL prompt, you can give any SQL commands. To exit from \nMySQL, just type quit.\nBy default, for security reasons, the MySQL service in Kali Linux \ncan be accessed only from a local machine. You can change this \nconfiguration by editing the bind-address stanza in the MySQL \nconfiguration file located in /etc/mysql/my.cnf. We don't \nrecommend that you change this behavior unless you want your \nMySQL to be accessed from other machines.\nTo stop the MySQL service, you can perform the following steps:\n1.\t In the graphical menu, navigate to Kali Linux | System Services | MySQL \n| mysql stop; or, from the command line, type the following:\nservice mysql stop\n2.\t Then, the system will respond with the following message:\n[ ok ] Stopping MySQL database server: mysqld.\nTo start the MySQL service automatically after Kali Linux's boots up, you can give \nthe following command:\nupdate-rc.d mysql defaults\nThis command will make the MySQL service start after the boot up.\n" }, { "page_number": 63, "text": "Beginning with Kali Linux\n[ 42 ]\nSSH\nFor the next service, we will look into the Secure Shell (SSH). SSH can be used to \nlog in to a remote machine securely; apart from that, there are several other usages of \nSSH, such as securely transferring a file between machines, executing a command in \na remote machine, and X11 session forwarding.\nTo manage your SSH service in Kali Linux, you can perform the following steps:\n1.\t To start the SSHD service from the graphical menu, navigate to Kali Linux \n| System Services | SSH | sshd start; or, from the command line, type the \nfollowing:\nservice ssh start\n2.\t The system will then respond with the following message:\n[ ok ] Starting OpenBSD Secure Shell server: sshd.\n3.\t To test your SSH, you can log in to the Kali Linux server from another server \nusing a SSH client such as putty (http://www.chiark.greenend.org.\nuk/~sgtatham/putty/) if you are using the Microsoft Windows operating \nsystem.\n4.\t To stop the SSHD service from the graphical menu, navigate to Kali Linux \n| System Services | SSH | sshd stop; or, from the command line, type the \nfollowing:\nservice ssh stop\n5.\t The system will then respond with the following message:\n[ ok ] Stopping OpenBSD Secure Shell server: sshd.\n6.\t To start the SSH service automatically after Kali Linux boots up, you can give \nthe following command:\nupdate-rc.d ssh defaults\nThis command will add the SSH service to be started on boot up.\n" }, { "page_number": 64, "text": "Chapter 1\n[ 43 ]\nInstalling a vulnerable server\nIn this section, we will install a vulnerable virtual machine as a target virtual \nmachine. This target will be used in several chapters of the book when we explain \nparticular topics. The reason we chose to set up a vulnerable server in our machine \ninstead of using vulnerable servers available on the Internet is because we don't want \nyou to break any laws. We should emphasize that you should never pen test other \nservers without written permission. Another purpose of installing another virtual \nmachine would be to improve your skills in a controlled manner. This way, it is easy \nto fix issues and understand what is going on in the target machine when attacks do \nnot work.\nIn several countries, even port scanning a machine that you don't own can be \nconsidered a criminal act. Also, if something happens to the operating system using \na virtual machine, we can repair it easily.\nThe vulnerable virtual machine that we are going to use is Metasploitable 2. This \nvulnerable system is created by the famous HD Moore of Rapid7. \nThere are other deliberately vulnerable systems besides Metasploitable \n2 that you can use for your penetration testing learning process, as \ncan be seen on the following site: http://www.felipemartins.\ninfo/2011/05/pentesting-vulnerable-study-frameworks-\ncomplete-list/.\nMetasploitable 2 has many vulnerabilities in the operating system, network, and web \napplication layers. \nInformation about the vulnerabilities contained in Metasploitable 2 can \nbe found on the Rapid7 site at https://community.rapid7.com/\ndocs/DOC-1875.\nTo install Metasploitable 2 in VirtualBox, you can perform the following steps:\n1.\t Download the Metasploitable 2 file from http://sourceforge.net/\nprojects/metasploitable/files/Metasploitable2/.\n2.\t Extract the Metasploitable 2 ZIP file. After the extraction process is completed \nsuccessfully, you will find five files:\n°°\nMetasploitable.nvram\n°°\nMetasploitable.vmdk\n°°\nMetasploitable.vmsd\n°°\nMetasploitable.vmx\n°°\nMetasploitable.vmxf\n" }, { "page_number": 65, "text": "Beginning with Kali Linux\n[ 44 ]\n3.\t Create a new virtual machine in VirtualBox. Set Name to Metasploitable2, \nOperating System to Linux, and Version to Ubuntu.\n4.\t Set the memory to 1024MB.\n5.\t In the Virtual Hard Disk setting, select Use existing hard disk. Choose the \nMetasploitable files that we have already extracted in the previous step:\n6.\t Change the network setting to Host-only adapter to make sure that this \nserver is accessible only from the host machine and the Kali Linux virtual \nmachine. The Kali Linux virtual machine's network setting should also be set \nto Host-only adapter for pen-testing local VMs.\n7.\t Start the Metasploitable 2 virtual machine. After the boot process is finished, \nyou can log in to the Metasploitable 2 console using the following credentials:\n°°\nUsername: msfadmin\n°°\nPassword: msfadmin\n8.\t The following is the Metasploitable 2 console after you have logged \nin successfully:\n" }, { "page_number": 66, "text": "Chapter 1\n[ 45 ]\nInstalling additional weapons\nAlthough the latest version of Kali Linux always comes with many security tools, \nsometimes you need to add additional software tools due to the following reasons:\n•\t\nThe latest version of the tool has not been included in Kali Linux yet\n•\t\nYou want to have the latest version of the software that is not available in the \nKali Linux repository\nOur suggestion is to try to search for the software package in the repository first. If \nyou can find the package in the repository, just use that package. However, if you \ncan't find it in the repository, you may want to get the software package from the \nauthor's website and install it yourself. \nBased on our experience, we suggest that you use the software in the repository as \nmuch as you can to ease the package management process.\nThere are several package management tools that can be used to help you manage \nthe software package in your system, such as dpkg, apt, and aptitude. Kali Linux \ncomes with dpkg and apt installed by default.\nIf you want to find out more about the apt and dpkg command, you \ncan go through the following references: https://help.ubuntu.\ncom/community/AptGet/Howto/ and http://www.debian.org/\ndoc/manuals/debian-reference/ch02.en.html.\n" }, { "page_number": 67, "text": "Beginning with Kali Linux\n[ 46 ]\nIn this section, we will briefly discuss the apt command in a practical way that is \nrelated to the software package installation process.\nTo search for a package name in the repository, you can use the following command:\napt-cache search \nThis command will display the entire software package that has the name package_\nname. For example, let's search for a software package called nessus; the following is \nthe command to do that:\napt-cache search nessus\nTo display more detailed information about a software package such as its \ndescription, size, and version, you can use the following command:\napt-cache show \nIf you want install the package or upgrade an individual software package, you can \nuse the apt-get command to install the package. The following is the basic syntax \nfor apt-get to do that:\napt-get install \nIf you can't find the package in the Kali Linux repository and are sure that the package \nwill not cause any problems in the future, you can install the package manually.\nDownload the software package only from trusted sources such as the software \ndeveloper's site. If the developer provides the .deb (the Debian package format) \npackages, you can use the dpkg command to install the additional software. If the \n.deb package is not provided, you can install the software from the source code. The \nactual process may vary but the general steps are usually similar to the following:\n1.\t Extract the software package using archiver programs such as Tar and 7-Zip.\n2.\t Change to the extracted directory.\n3.\t Run the following commands:\n ./configure\nmake\nmake installh\n" }, { "page_number": 68, "text": "Chapter 1\n[ 47 ]\nIn this section, we will provide you with examples on how to install several \nadditional security tools that are not available from the Kali Linux repository. We \nwill give various mechanisms that can be used to install the software:\n•\t\nDownloading the Debian package and installing it\n•\t\nDownloading from the source package and installing it\nInstalling the Nessus vulnerability scanner\nAs an example, we want to install the latest Nessus vulnerability scanner (Version 5) \nfor the first installation mechanism. We have searched the Kali Linux repository but \nare unable to find Nessus. \nNessus Version 5 has many new features as compared to Nessus Version 4, such as \nmore flexible results filtering and report creation and simplified policy creation; we \nchose to use this version instead of Nessus Version 4. \nYou can find more information about the features and enhancement \nin Nessus Version 5 from http://www.tenable.com/products/\nnessus/nessus-product-overview/why-upgrade-to-nessus-5.\nWe can download the latest Nessus package generated for Debian 6 Linux distribution \nfrom the Nessus website (http://www.nessus.org/products/nessus/nessus-\ndownload-agreement). To install this package, we issue the following command:\ndpkg -i Nessus-x.y.z-debian6_i386.deb\nWe used x.y.z in the previous command to denote the Nessus \nversion number. You need to change those numbers to the Nessus \nversion that you just downloaded successfully.\nYou can then follow the instructions given on the screen to configure your \nNessus server:\n1.\t Start the Nessus server by typing the following if it has not started yet:\n/etc/init.d/nessusd start\n" }, { "page_number": 69, "text": "Beginning with Kali Linux\n[ 48 ]\n2.\t Open your browser and connect to https://localhost:8834. You will then \nbe prompted with a warning about an invalid SSL certificate used by Nessus. \nYou need to check the SSL certificate and then store the exception for that \nSSL certificate. The following is the Nessus page that will be shown after you \nhave stored the SSL certificate exception:\n3.\t After that, you will be guided to create a Nessus admin credential. Next, you \nwill be asked to enter your activation code to register the Nessus scanner to \nTenable. You need to register at http://www.nessus.org/register/ to \nobtain the activation code: \n" }, { "page_number": 70, "text": "Chapter 1\n[ 49 ]\n4.\t After you have registered successfully, you will be able to download the \nnewest Nessus plugins. The plugins download process will take some time to \ncomplete; you can do something else while waiting for the download process \nto finish.\nInstalling the Cisco password cracker\nFor the second example, we will use a simple program called cisco_crack (http://\ninsecure.org/sploits/cisco.passwords.html). This tool is used to crack the \nCisco type 7 password.\nCisco type 7 password is a very weak password, so it should not be \nused anymore. However, for penetration testing, we see that it is still \nbeing used, although it's not widespread anymore. This tool will be a \nhelp for this occasion.\nAfter downloading the source code, the next step is to compile it. Before you can \ncompile the source code cleanly, you need to add the following include statements:\n#include \n#include \nNow, you have four include statements in the source code.\nTo compile the code, you can just give the following command:\ngcc cisco_crack.c –o cisco_crack\nIf there is no error, an executable file with the name of cisco_crack will be created. \nThe following is the help screen of cisco_crack:\n# ./cisco_crack -h\nUsage: ./cisco_crack -p \n ./cisco_crack \nSummary\nThis chapter introduced you to the amazing world of Kali Linux, which is a Live \nDVD Linux distribution that has been specially developed to help you in the \npenetration testing process. Kali is the successor of BackTrack, a famous Linux \ndistribution focused on the purpose of penetration testing.\n" }, { "page_number": 71, "text": "Beginning with Kali Linux\n[ 50 ]\nThe chapter started with a brief description of Kali Linux's history. Next, it moved \non to see what functionalities Kali Linux has to offer. The latest version of Kali Linux \nhas many tools to help in penetration testing. Additionally, it also has tools for \ndigital forensics, wireless, reverse engineering, and hardware hacking tasks.\nThe discussion continues on how to get Kali Linux and the several ways to install it. \nKali Linux can be used as a Live DVD without installing it to the hard disk. It can be \ninstalled to the hard disk and can also be used as a portable distribution by installing \nit to a USB flash disk.\nBefore Kali Linux can be used properly in penetration testing, it needs to be \nconfigured for the network connection, using either a wired or wireless connection. \nWe also discussed how to use several features in the VirtualBox machine to make \nit easier to work with the virtual machine; for example, installing additional tools, \nconfiguring shared folders, exporting the virtual machine for a backup purpose or \nto share it with other people, and taking a snapshot to back up the virtual machine \ntemporarily.\nAs with any other software, Kali Linux also needs to be updated, whether we only \nupdate the software applications or the Linux kernel included in the distribution. \nYou may need to test your penetration testing skills; unfortunately, you don't have \npermission to do this to other servers as it is considered illegal in several countries. \nTo help you with this, there are several intentionally vulnerable systems that \ncan be installed and used on your own machine. In this chapter, we looked into \nMetasploitable 2 from Rapid7.\nWe also discussed several network services included with the latest Kali Linux, such \nas HTTP, MySQL, and SSH. We started by giving you a brief introduction to each \nservice and then we continue with how to manage the service; for example, how to \nstart or stop the service.\nAt the end of the chapter, we looked at installing additional information security \ntools that are not included in the latest Kali Linux version by default, such as the \nNessus network scanner and Cisco password cracker.\nIn the next chapter, we will introduce you to several penetration testing \nmethodologies.\n" }, { "page_number": 72, "text": "Penetration Testing \nMethodology\nPenetration testing, often abbreviated as pentest, is a process that is followed \nto conduct an in-depth security assessment or audit. A methodology defines a \nset of rules, practices, and procedures that are pursued and implemented during \nthe course of any information security audit program. A penetration testing \nmethodology defines a roadmap with practical ideas and proven practices that can \nbe followed to assess the true security posture of a network, application, system, or \nany combination thereof. This chapter offers summaries of several key penetration \ntesting methodologies. Key topics covered in this chapter include:\n•\t\nA discussion on two well-known types of penetration testing—black box and \nwhite box\n•\t\nDescribing the differences between the vulnerability assessment and \npenetration testing\n•\t\nExplaining several industry-acceptable security testing methodologies and \ntheir core functions, features, and benefits\n•\t\nA general penetration testing methodology that incorporates the 10 \nconsecutive steps of a typical penetration testing process \n•\t\nThe ethical dimension of how the security testing projects should be handled\nPenetration testing can be carried out independently or as a part of an IT security \nrisk management process that may be incorporated into a regular development life \ncycle (for example, Microsoft SDLC). It is vital to notice that the security of a product \nnot only depends on the factors that are related to the IT environment but also relies \non product-specific security best practices. This involves the implementation of \nappropriate security requirements, performing risk analysis, threat modeling, code \nreviews, and operational security measurement. \n" }, { "page_number": 73, "text": "Penetration Testing Methodology\n[ 52 ]\nPenetration testing is considered to be the last and most aggressive form of security \nassessment. It must be handled by qualified professionals and can be conducted with \nor without prior knowledge of the targeted network or application. A pentest may \nbe used to assess all IT infrastructure components including applications, network \ndevices, operating systems, communication medium, physical security, and human \npsychology. The output of penetration testing usually consists of a report divided \ninto several sections that address the weaknesses found in the current state of the \ntarget environment, followed by potential countermeasures and other remediation \nrecommendations. The use of a methodological process provides extensive benefits \nto the pentester to understand and critically analyze the integrity of current defenses \nduring each stage of the testing process.\nTypes of penetration testing\nAlthough there are different types of penetration testing, the two most general \napproaches that are widely accepted by the industry are the black box and white box. \nThese approaches will be discussed in the following sections.\nBlack box testing\nWhile applying this approach, the security auditor will be assessing the network \ninfrastructure and will not be aware of any internal technologies deployed by the \ntargeted organization. By employing a number of real-world hacker techniques and \ngoing through organized test phases, vulnerabilities may be revealed and potentially \nexploited. It is important for a pentester to understand, classify, and prioritize these \nvulnerabilities according to their level of risk (low, medium, or high). The risk can be \nmeasured according to the threat imposed by the vulnerability in general. An ideal \npenetration tester would determine all attack vectors that could cause the target to \nbe compromised. Once the testing process has been completed, a report that contains \nall the necessary information regarding the targets' real-world security posture, \ncategorizing, and translating the identified risks into a business context, is generated. \nBlack box testing can be a more expensive service than white box testing.\n" }, { "page_number": 74, "text": "Chapter 2\n[ 53 ]\nWhite box testing\nAn auditor involved in this kind of penetration testing process should be aware of all \nthe internal and underlying technologies used by the target environment. Hence, it \nopens a wide gate for a penetration tester to view and critically evaluate the security \nvulnerabilities with minimum possible efforts and utmost accuracy. It does bring \nmore value to the organization in comparison to the black box approach in the sense \nthat it will eliminate any internal security issues lying at the target infrastructure's \nenvironment, thus making it more difficult for a malicious adversary to infiltrate \nfrom the outside. The number of steps involved in white box testing is similar to \nthat of black box testing. Moreover, the white box approach can easily be integrated \ninto a regular development life cycle to eradicate any possible security issues at \nan early stage before they get disclosed and exploited by intruders. The time, cost, \nand knowledge level required to find and resolve the security vulnerabilities is \ncomparably less than with the black box approach.\nVulnerability assessment versus \npenetration testing\nThere is always a need to understand and practice the correct terminology for \nsecurity assessment. Throughout your career, you may run into commercial grade \ncompanies and non-commercial organizations that are likely to misinterpret the term \npenetration testing when trying to select an assessment type. It is important that you \nunderstand the differences between these types of tests. \nVulnerability assessment is a process to assess the internal and external security \ncontrols by identifying the threats that pose serious exposure to the organizations' \nassets. This technical infrastructure evaluation not only points to the risks in the \nexisting defenses, but also recommends and prioritizes the remediation strategies. \nThe internal vulnerability assessment provides you with an assurance to secure \nthe internal systems, while the external vulnerability assessment demonstrates the \nsecurity of the perimeter defenses. In both testing criteria, each asset on the network \nis rigorously tested against multiple attack vectors to identify unattended threats \nand quantify the reactive measures. Depending on the type of assessment being \ncarried out, a unique set of testing processes, tools, and techniques are followed to \ndetect and identify vulnerabilities in the information assets in an automated fashion. \nThis can be achieved using an integrated vulnerability management platform that \nmanages an up-to-date vulnerabilities database and is capable of testing different \ntypes of network devices while maintaining the integrity of configuration and \nchange management.\n" }, { "page_number": 75, "text": "Penetration Testing Methodology\n[ 54 ]\nA key difference between the vulnerability assessment and penetration testing is \nthat the penetration testing goes beyond the level of identifying vulnerabilities and \nhooks into the process of exploitation, privilege escalation, and maintaining access \nto the target system(s). On the other hand, vulnerability assessment provides you \nwith a broad view of any existing flaws in the system without measuring the impact \nof these flaws to the system under consideration. Another major difference between \nboth of these terms is that the penetration testing is considerably more intrusive than \nthe vulnerability assessment and aggressively applies all of the technical methods \nto exploit the live production environment. However, the vulnerability assessment \nprocess carefully identifies and quantifies all the known vulnerabilities in a \nnon-invasive manner.\nWhy penetration testing?\nWhen there is doubt that mitigating controls such as firewalls, intrusion \ndetection systems, file integrity monitoring, and so on are effective, a full \npenetration test is ideal. Vulnerability scanning will locate individual \nvulnerabilities; however, penetration testing will actually attempt to verify \nthat these vulnerabilities are exploitable within the target environment.\nThis perception, while dealing with both of these assessment types, might confuse \nand overlap the terms interchangeably, which is absolutely wrong. A qualified \nconsultant always attempts to work out the best type of assessment based on the \nclient's business requirement rather than misleading them from one over the other. \nIt is also the duty of the contracting party to look into the core details of the selected \nsecurity assessment program before taking any final decision.\nPenetration testing is an expensive service in comparison to \nvulnerability assessment.\nSecurity testing methodologies\nVarious open source methodologies have been created to address the security \nassessment's needs. Using these assessment methodologies, one can strategically \naccomplish the time-critical and challenging task of assessing the system's security \nregardless of its size and complexity. Some methodologies focus on the technical \naspect of security testing, while others focus on managerial criteria, and very few \naddress both sides. The basic idea behind formalizing these methodologies with your \nassessment is to execute different types of tests step-by-step in order to accurately \njudge the security posture of a system. \n" }, { "page_number": 76, "text": "Chapter 2\n[ 55 ]\nTherefore, you will be introduced to several well-known security assessment \nmethodologies that provide you with an extended view of the assessing network \nand application security by highlighting their key features and benefits. These \ninclude the following: \n•\t\nOpen Source Security Testing Methodology Manual\n•\t\nInformation Systems Security Assessment Framework\n•\t\nOpen Web Application Security Project Testing Guide\n•\t\nWeb Application Security Consortium Threat Classification \n•\t\nPenetration Testing Execution Standard\nAll of these testing frameworks and methodologies will assist security professionals \nchoose the best strategy that adheres to their client's requirements. The first two \nprovide you with general guidelines and methods of security testing for almost \nany type of information asset. The testing frameworks provided by Open Web \nApplication Security Project (OWASP) and Web Application Security Consortium \n(WASC) primarily deal with the assessment of application security. Penetration \nTesting Execution Standard (PTES) will provide you with guidance on all types of \npenetration testing efforts. It is, however, important to note that security is an on-\ngoing process in itself and a penetration test is a snapshot that details the security \nposture at the time of the test. Any minor change in the target environment may \naffect the entire process of security testing and could introduce errors in the final \nresults. Additionally, adapting any single methodology does not necessarily provide \nyou with a complete picture of the risk assessment process. It is left to the security \nauditor to select the best strategy that could address the target testing criteria.\nThere are many security testing methodologies; choosing the best one requires a \ncareful selection process through which one can determine the cost and effectiveness \nof the assessment. Thus, determining the right assessment strategy depends on \nseveral factors, including the technical details provided about the target environment \nand resource availability, pentester's knowledge, business objectives, and regulatory \nconcerns. From a business standpoint, efficiency and cost control is of extreme \nimportance. Each of the following testing methodologies have very detailed and \nwell-written documentation at their respective sites. We provide a brief summary \nof each, but to truly understand how they work in detail, you need to go to their \nrespective websites and carefully study the documentation and implementation \ndetails provided by their creators. \n" }, { "page_number": 77, "text": "Penetration Testing Methodology\n[ 56 ]\nOpen Source Security Testing Methodology \nManual (OSSTMM)\nOpen Source Security Testing Methodology Manual (OSSTMM) (http://www.\nisecom.org/research/osstmm.html) is a recognized international standard \ncreated by Pete Herzog and developed by ISECOM for security testing and analysis. \nIt's being used by many organizations in their day-to-day assessment cycle. From \na technical perspective, its methodology is divided into four key groups—scope, \nchannel, index, and vector. The scope defines a process of collecting information on \nall assets that operate in the target environment. A channel determines the type of \ncommunication and interaction with these assets, which can be physical, spectrum, \nand communication. All of these channels depict a unique set of security components \nthat must be tested and verified during the assessment period. These components \nare comprised of physical security, human psychology, data networks, wireless \ncommunication medium, and telecommunication. The index is a method that is used \nto classify target assets that correspond to their particular identifications, such as \nMAC Address and IP Address. At the end, a vector concludes the direction through \nwhich an auditor can assess and analyze each functional asset. The whole process \ninitiates a technical roadmap that evaluates the target environment thoroughly and is \nknown as audit scope.\nThere are different forms of security testing that have been classified under the \nOSSTMM methodology, and their organization is presented within six standard \nsecurity test types:\n•\t\nBlind: Blind testing does not require any prior knowledge about the target \nsystem. However, the target is informed before the execution of an audit \nscope. Ethical hacking and war gaming are examples of blind type testing. \nThis kind of testing is also widely accepted because of its ethical vision of \ninforming a target in advance.\n•\t\nDouble blind: In double blind testing, an auditor neither requires any \nknowledge about the target system, nor is the target informed before the test \nexecution. Black box auditing and penetration testing are examples of double \nblind testing. Most of the security assessments today are carried out using \nthis strategy, thus putting a real challenge for the auditors to select the best of \nbreed tools and techniques in order to achieve their required goal. \n•\t\nGray box: In gray box testing, an auditor holds limited knowledge about \nthe target system and the target is also informed before the test is executed. \nVulnerability assessment is one of the basic examples of gray box testing. \n" }, { "page_number": 78, "text": "Chapter 2\n[ 57 ]\n•\t\nDouble gray box: Double gray box testing works in a way that is similar to \ngray box testing, except that the time frame for an audit is defined and there \nare no channels and vectors being tested. White box audit is an example of \ndouble gray box testing.\n•\t\nTandem: In tandem testing, the auditor holds minimum knowledge to assess \nthe target system and the target is also notified in advance, before the test is \nexecuted. Note that tandem testing is conducted thoroughly. Crystal box and \nin-house audit are examples of tandem testing.\n•\t\nReversal: In reversal testing, an auditor holds full knowledge of the target \nsystem and the target will never be informed of how and when the test will \nbe conducted. \nThe technical assessment framework provided by OSSTMM is flexible and capable \nof deriving certain test cases that are logically divided into five security components \nof three consecutive channels, as mentioned previously. These test cases generally \nexamine the target by assessing its access control security, process security, data \ncontrols, physical location, perimeter protection, security awareness level, trust level, \nfraud control protection, and many other procedures. The overall testing procedures \nfocus on what is to be tested, how it should be tested, what tactics should be applied \nbefore, during, and after the test, and how to interpret and correlate the final results. \nCapturing the current state of the protection of a target system is considerably useful \nand invaluable. Thus, the OSSTMM methodology has introduced this terminology in \nthe form of RAV (Risk Assessment Values). The basic function of RAV is to analyze \nthe test results and compute the actual security value based on three factors, which \nare operational security, loss controls, and limitations. This final security value is \nknown as RAV score. By using RAV score, an auditor can easily extract and define \nthe milestones based on the current security posture to accomplish better protection. \nFrom a business perspective, RAV can optimize the amount of investment required \non security and might help you with the justification of investing in more effective \nsecurity solutions.\nKey features and benefits\nThe following are the key features and benefits of OSSTMM:\n•\t\nPracticing the OSSTMM methodology substantially reduces the occurrence \nof false negatives and false positives and provides reproducible security \nmeasurements. \n•\t\nThe framework is adaptable to many types of security tests, such as \npenetration testing, white box audit, vulnerability assessment, and so forth.\n•\t\nIt ensures that the assessment should be carried out thoroughly and the \nresults are collected in a consistent, quantifiable, and reliable manner.\n" }, { "page_number": 79, "text": "Penetration Testing Methodology\n[ 58 ]\n•\t\nThe methodology itself follows a process of four individually connected \nphases, namely, definition phase, information phase, regulatory phase, \nand controls test phase. Each of these obtains, assesses, and verifies the \ninformation regarding the target environment.\n•\t\nRAV calculates the actual security value based on operational security, \nloss controls, and limitations. The given output, known as the RAV score, \nrepresents the current state of target security.\n•\t\nFormalizing an assessment report using the Security Test Audit Report \n(STAR) template can be advantageous to management as well as the \ntechnical team when reviewing the testing objectives, risk assessment values, \nand the output of each test phase.\n•\t\nThe methodology is regularly updated with new trends of security testing, \nregulations, and ethical concerns.\n•\t\nThe OSSTMM process can be coordinated with industry regulations, business \npolicy, and government legislations. Additionally, a certified audit can also \nbe eligible for accreditation from ISECOM (Institute for Security and Open \nMethodologies) directly.\nInformation Systems Security Assessment \nFramework (ISSAF)\nInformation Systems Security Assessment Framework (ISSAF) (www.oissg.\norg/issaf) is another open source security testing and analysis framework. Its \nframework has been categorized into several domains to address the security \nassessment in a logical order. Each of these domains assesses different parts of a \ntarget system and provides field inputs for the successful security engagement. \nBy integrating its framework into a regular business life cycle, it may provide the \naccuracy, completeness, and efficiency required to fulfill an organization's security \ntesting requirements. ISSAF was developed to focus on two areas of security \ntesting—technical and managerial. The technical side establishes the core set of \nrules and procedures to follow and create an adequate security assessment process, \nwhile the managerial side accomplishes engagement with the management and \nthe best practices that should be followed throughout the testing process. It should \nbe remembered that ISSAF defines the assessment as a process instead of an audit. \nAs auditing requires a more established body to proclaim the necessary standards, \nits assessment framework does include the planning, assessment, treatment, \naccreditation, and maintenance phases. Each of these phases holds generic guidelines \nthat are effective and flexible for any organizational structure. \n" }, { "page_number": 80, "text": "Chapter 2\n[ 59 ]\nThe output is a combination of operational activities, security initiatives, and a \ncomplete listing of vulnerabilities that might exist in the target environment. The \nassessment process chooses the shortest path to reach the test deadline by analyzing \nits target against critical vulnerabilities that can be exploited with minimum effort.\nISSAF contains a rich set of technical assessment baselines to test the number of \ndifferent technologies and processes. However, this has introduced another problem \nof maintenance to keep updating the framework in order to reflect new or updated \ntechnology assessment criteria. When compared to the OSSTMM methodology, these \nobsolescence issues affect the OSSTMM less, because the auditor is able to use the \nsame methodology over the number of security engagements using a different set of \ntools and techniques. On the other hand, ISSAF also claims to be a broad framework \nwith up-to-date information on security tools, best practices, and administrative \nconcerns to complement the security assessment program. It can also be aligned with \nOSSTMM or any other similar testing methodology, thus combining the strengths of \neach other. \nKey features and benefits\nThe following are the key features and benefits of ISSAF:\n•\t\nISSAF provides you with a high value proposition to secure the infrastructure \nby assessing the existing security controls against critical vulnerabilities.\n•\t\nIt addresses different key areas of information security. These include risk \nassessment, business structure and management, controls assessment, \nengagement management, security policies development, and general \nbest practices.\n•\t\nISSAF penetration testing methodology examines the security of a network, \nsystem, or application. The framework can transparently focus on target-\nspecific technology that may involve routers, switches, firewalls, intrusion \ndetection and prevention systems, storage area networks, virtual private \nnetworks, various operation systems, web application servers, databases, and \nso forth.\n•\t\nIt bridges the gap between the technical and managerial view of security \ntesting by implementing the necessary controls to handle both areas.\n•\t\nIt enables the management to understand the existing risks that float over \nan organization's perimeter defenses and reduces them proactively by \nidentifying the vulnerabilities that may affect the business integrity.\nOSSTMM and ISSAF can be used in combination with each other to \nassess the security of an enterprise environment.\n" }, { "page_number": 81, "text": "Penetration Testing Methodology\n[ 60 ]\nOpen Web Application Security Project \n(OWASP) \nThe Open Web Application Security Project (OWASP) open community brings its \ntop 10 project forward to increase the awareness of application security. The project \nprovides you with a necessary foundation to integrate security through secure \ncoding principles and practices. OWASP also provides you with a wonderful testing \nguide as part of the OWASP Testing Project (https://www.owasp.org/index.php/\nOWASP_Testing_Project) that should be carefully reviewed to determine if this \nframework can assist you in your efforts.\nThe OWASP top 10 project categorizes the application security risks by evaluating \nthe top attack vectors and security weaknesses in relation to their technical and \nbusiness impact. While assessing the application, each of these risks demonstrates a \ngeneric attack method that is independent of the technology or platform being used. \nIt also provides you with specific instructions on how to test, verify, and remediate \neach vulnerable part of an application. The OWASP top 10 mainly focuses on the \nhigh risk problem areas rather than addressing all the issues that surround the \nweb application's security. However, some essential guidelines are available in the \nOWASP community for developers and security auditors to effectively manage the \nsecurity of web applications:\n•\t\nThe Testing Guide: https://www.owasp.org/index.php/OWASP_Testing_\nGuide_v3_Table_of_Content\n•\t\nThe Developer's Guide: www.owasp.org/index.php/Guide\n•\t\nThe Code Review Guide: www.owasp.org/index.php/Category:OWASP_\nCode_Review_Project\nThe OWASP top 10 changes on a year-to-year basis. For detailed information, visit \nthe project's website at https://www.owasp.org/index.php/Category:OWASP_\nTop_Ten_Project.\nKey features and benefits\nThe following are the key features and benefits of OWASP:\n•\t\nTesting web applications against OWASP top ten security risks ensures \nthat the most common attacks and weaknesses are avoided and the \nconfidentiality, integrity, and availability of an application is maintained.\n•\t\nThe OWASP community has developed a number of security tools that focus \non the automated and manual web application tests. A few of these tools are \nWebScarab, Wapiti, JBroFuzz, and SQLiX, which are also available under the \nKali Linux operating system.\n" }, { "page_number": 82, "text": "Chapter 2\n[ 61 ]\n•\t\nWhen considering the security assessment of web infrastructure, the \nOWASP Testing Guide provides you with technology-specific assessment \ndetails; for instance, the testing of Oracle is approached differently than \nMySQL. Such a guide provides you with a wider and more collaborative \nlook at multiple technologies, which helps an auditor choose the best-suited \nprocedure for testing.\n•\t\nIt encourages the secure coding practices for developers by integrating \nsecurity tests at each stage of development. This will ensure that the \nproduction application is robust, error-free, and secure.\n•\t\nIt provides industry-wide acceptance and visibility. The top ten security \nrisks can also be aligned with other web application security assessment \nstandards, thus helping you achieve more than one standard at a time with a \nlittle more effort.\nWeb Application Security Consortium Threat \nClassification (WASC-TC)\nIdentifying the application's security risks requires a thorough and rigorous testing \nprocedure, which can be followed throughout the development's life cycle. WASC \nthreat classification is another such open standard to assess the security of web \napplications. Similar to the OWASP standard, it is also classified into a number of \nattacks and weaknesses but addresses them in a much deeper fashion. Practicing this \nblack art for identification and verification of threats that are hanging over the web \napplication requires standard terminology to be followed, which can quickly adapt \nto the technology environment. This is where the WASC-TC comes in very handy. \nThe overall standard is presented in three different views to help developers and \nsecurity auditors understand the vision of web application security threats:\n•\t\nEnumeration view: This view is dedicated to providing the basis for web \napplication attacks and weaknesses. Each of these attacks and weaknesses \nhave been discussed individually with its concise definition, type, and \nexamples of multiple programming platforms. Additionally, it is in line with \nits unique identifier, which can be useful for referencing. A total of 49 attacks \nand weaknesses are collated with a static WASC-ID number (1 to 49). Note \nthat this numeric representation does not focus on the risk severity but serves \nthe purpose of referencing instead.\n" }, { "page_number": 83, "text": "Penetration Testing Methodology\n[ 62 ]\n•\t\nDevelopment view: The development view takes the developer's \npanorama forward by combining the set of attacks and weaknesses into \nvulnerabilities, which are likely to occur at any of three consecutive \ndevelopment phases. This could be a design, implementation, or deployment \nphase. The design vulnerabilities are introduced when the application's \nrequirements do not fulfill the security at the initial stage of requirement \ngathering. The implementation vulnerabilities occur due to insecure coding \nprinciples and practices. The deployment vulnerabilities are the result of \nthe misconfiguration of the application, web server, and other external \nsystems. Thus, the view broadens the scope for its integration into a regular \ndevelopment life cycle as a part of best practices.\n•\t\nTaxonomy cross-reference view: Referring to a cross-reference view \nof multiple web application security standards can help auditors and \ndevelopers map the terminology presented in one standard with another. \nWith a little more effort, the same facility can also assist you in achieving \nmultiple standard compliances at the same time. However, each application's \nsecurity standard defines it own criteria to assess the applications from \ndifferent angles and measures their associated risks in general. Thus, each \nstandard requires different efforts to be made to scale up the calculation \nfor risks and their severity levels. The WASC-TC attacks and weaknesses \npresented in this category are mapped with OWASP top 10, Mitre's \nCommon Weakness Enumeration (CWE), Mitre's Common Attack Pattern \nEnumeration and Classification (CAPEC), and SANS-CWE top 25 list.\nMore details regarding Mitre's CWE can be found at https://cwe.\nmitre.org/.\nMore information regarding Mitre's CAPEC can be found at http://\ncapec.mitre.org/.\nSANS-CWE top 25 list can be found at http://www.sans.org/top25-\nsoftware-errors/.\nMore details regarding WASC-TC and its views can be found at http://\nprojects.webappsec.org/Threat-Classification.\nKey features and benefits\nThe following are the key features and benefits of the WASC-TC:\n•\t\nWASC-TC provides you with in-depth knowledge to assess the web \napplication environment against the most common attacks and weaknesses.\n•\t\nThe attacks and weaknesses presented by WASC-TC can be used to test and \nverify any web application platform using a combination of tools from the \nKali Linux operating system.\n" }, { "page_number": 84, "text": "Chapter 2\n[ 63 ]\n•\t\nThe standard provides you with three different views, namely, enumeration, \ndevelopment, and cross-reference. Enumeration serves as a base for all the \nattacks and weaknesses found in the web applications. The development \nview merges these attacks and weaknesses into vulnerabilities and \ncategorizes them according to their occurrence in the relative development \nphase. This could be a design, implementation, or deployment phase. The \ncross-reference view serves the purpose of referencing other application \nsecurity standards with WASC-TC. \n•\t\nWASC-TC has already acquired industry-level acceptance and its integration \ncan be found in many open source and commercial solutions, mostly in \nvulnerability assessment and managerial products.\n•\t\nIt can also be aligned with other well-known application security standards, \nsuch as OWASP and SANS-CWE.\nPenetration Testing Execution Standard \n(PTES)\nThe Penetration Testing Execution Standard (PTES) was created by some of the \nbrightest minds and definitive experts in the penetration testing industry. It consists \nof seven phases of penetration testing and can be used to perform an effective \npenetration test on any environment. The details of the methodology can be found at \nhttp://www.pentest-standard.org/index.php/Main_Page.\nThe seven stages of penetration testing that are detailed by this standard are as \nfollows (source: www.pentest-standard.org):\n•\t\nPre-engagement interactions\n•\t\nIntelligence gathering\n•\t\nThreat modeling\n•\t\nVulnerability analysis\n•\t\nExploitation\n•\t\nPost-exploitation\n•\t\nReporting\nEach of these stages is provided in detail on the PTES site along with specific mind \nmaps that detail the steps required for each phase. This allows for the customization \nof the PTES standard to match the testing requirements of the environments that are \nbeing tested. More details about each step can be accessed by simply clicking on the \nitem in the mind map. \n" }, { "page_number": 85, "text": "Penetration Testing Methodology\n[ 64 ]\nKey features and benefits\nThe following are the key features and benefits of the PTES:\n•\t\nIt is a very thorough penetration testing framework that covers the technical \nas well as other important aspects of a penetration test, such as scope creep, \nreporting, and protecting you as a penetration tester\n•\t\nIt has detailed instructions on how to perform many of the tasks that are \nrequired to accurately test the security posture of an environment\n•\t\nIt is put together for penetration testers by experienced penetration testing \nexperts who perform these tasks on a daily basis\n•\t\nIt is inclusive of the most commonly found technologies as well as ones that \nare not so common\n•\t\nIt is easy to understand and you can adapt it to your own testing needs\nGeneral penetration testing framework\nKali Linux is a versatile operating system that comes with a number of security \nassessment and penetration testing tools. Deriving and practicing these tools without \na proper framework can lead to unsuccessful testing and might produce unsatisfied \nresults. Thus, formalizing the security testing with a structured framework is \nextremely important from a technical and managerial perspective. \nThe general testing framework presented in this section will constitute both the \nblack box and white box approaches. It offers you a basic overview of the typical \nphases through which an auditor or penetration tester should progress. Either of \nthese approaches can be adjusted according to the given target of assessment. The \nframework is composed of a number of steps that should be followed in a process \nat the initial, medial, and final stages of testing in order to accomplish a successful \nassessment. These include the following:\n•\t\nTarget scoping \n•\t\nInformation gathering\n•\t\nTarget discovery\n•\t\nEnumerating target\n•\t\nVulnerability mapping \n•\t\nSocial engineering\n•\t\nTarget exploitation\n•\t\nPrivilege escalation\n" }, { "page_number": 86, "text": "Chapter 2\n[ 65 ]\n•\t\nMaintaining access\n•\t\nDocumentation and reporting\nWhether applying any combination of these steps with the black box or white box \napproaches, it is left to the penetration tester to decide and choose the most strategic \npath according to the given target environment and its prior knowledge before the \ntest begins. We will explain each stage of testing with a brief description, definition, \nand its possible applications. This general approach may be combined with any \nof the existing methodologies and should be used as a guideline rather than a \npenetration testing catch-all solution. \nTarget scoping\nBefore starting the technical security assessment, it is important to observe and \nunderstand the given scope of the target network environment. It is also necessary to \nknow that the scope can be defined for a single entity or set of entities that are given \nto the auditor. The following list provides you with typical decisions that need to be \nmade during the target scoping phase:\n•\t\nWhat should be tested?\n•\t\nHow should it be tested?\n•\t\nWhat conditions should be applied during the test process?\n•\t\nWhat will limit the execution of the test process?\n•\t\nHow long will it take to complete the test?\n•\t\nWhat business objectives will be achieved?\nTo lead a successful penetration testing, an auditor must be aware of the \ntechnology under assessment, its basic functionality, and its interaction with the \nnetwork environment. Thus, the knowledge of an auditor does make a significant \ncontribution towards any kind of security assessment.\nInformation gathering\nOnce the scope is finalized, it is time to move into the reconnaissance phase. During \nthis phase, a pentester uses a number of publicly available resources to learn more \nabout his or her target. This information can be retrieved from Internet sources such as:\n•\t\nForums\n•\t\nBulletin boards\n•\t\nNewsgroups\n" }, { "page_number": 87, "text": "Penetration Testing Methodology\n[ 66 ]\n•\t\nArticles\n•\t\nBlogs \n•\t\nSocial networks \n•\t\nCommercial or non-commercial websites \nAdditionally, the data can also be gathered through various search engines, such \nas Google, Yahoo!, MSN Bing, Baidu, and others. Moreover, an auditor can use the \ntools provided in Kali Linux to extract the network information about a target. These \ntools perform valuable data mining techniques to collect information through DNS \nservers, trace routes, Whois database, e-mail addresses, phone numbers, personal \ninformation, and user accounts. As more information is gathered, the probability of \nconducting a successful penetration test is increased.\nTarget discovery\nThis phase mainly deals with identifying the target's network status, operating \nsystem, and its relative network architecture. This provides you with a complete \nimage of the interconnected current technologies or devices and may further help \nyou in enumerating various services that are running over the network. By using \nthe advanced network tools from Kali Linux, one can determine the live network \nhosts, operating systems running on these host machines, and characterize each \ndevice according to its role in the network system. These tools generally implement \nactive and passive detection techniques on the top of network protocols, which can \nbe manipulated in different forms to acquire useful information such as operating \nsystem fingerprinting.\nEnumerating target\nThis phase takes all the previous efforts forward and finds the open ports on the \ntarget systems. Once the open ports have been identified, they can be enumerated \nfor the running services. Using a number of port scanning techniques such as full-\nopen, half-open, and stealth scan can help determine the port's visibility even if the \nhost is behind a firewall or Intrusion Detection System (IDS). The services mapped \nto the open ports help in further investigating the vulnerabilities that might exist \nin the target network's infrastructure. Hence, this phase serves as a base for finding \nvulnerabilities in various network devices, which can lead to a serious penetration. \nAn auditor can use some automated tools given in Kali Linux to achieve the goal of \nthis phase.\n" }, { "page_number": 88, "text": "Chapter 2\n[ 67 ]\nVulnerability mapping\nUp until the previous phase, we have gathered sufficient information about the \ntarget network. It is now time to identify and analyze the vulnerabilities based \non the disclosed ports and services. This process can be achieved via a number of \nautomated network and application vulnerability assessment tools that are present \nunder the Kali Linux OS. It can also be done manually but takes an enormous \namount of time and requires expert knowledge. However, combining both \napproaches should provide an auditor with a clear vision to carefully examine any \nknown or unknown vulnerability that may otherwise exist on the network systems. \nSocial engineering\nPracticing the art of deception is considerably important when there is no open \ngate available for an auditor to enter the target network. Thus, using a human \nattack vector, it is still possible to penetrate the target system by tricking a user into \nexecuting malicious code that should give backdoor access to the auditor. Social \nengineering comes in different forms. This can be anybody pretending to be a network \nadministrator over the phone forcing you to reveal your account information or an \ne-mail phishing scam that can hijack your bank account details. Someone imitating \npersonnel to get into a physical location is also considered social engineering. There is \nan immense set of possibilities that could be applied to achieve the required goal. Note \nthat for a successful penetration, additional time to understand human psychology \nmay be required before applying any suitable deception against the target. It is also \nimportant to fully understand the associated laws of your country with regards to \nsocial engineering prior to attempting this phase.\nTarget exploitation\nAfter carefully examining the discovered vulnerabilities, it is possible to penetrate \nthe target system based on the types of exploits that are available. Sometimes, it may \nrequire additional research or modifications to the existing exploit in order to make \nit work properly. This sounds a bit difficult but might get easier when considering \na work under advanced exploitation tools, which are already provided with Kali \nLinux. Moreover, an auditor can also apply client-side exploitation methods mixed \nwith a little social engineering to take control of a target system. Thus, this phase \nmainly focuses on the target acquisition process. The process coordinates three core \nareas, which involve pre-exploitation, exploitation, and post-exploitation activities.\n" }, { "page_number": 89, "text": "Penetration Testing Methodology\n[ 68 ]\nPrivilege escalation\nOnce the target is acquired, the penetration is successful. An auditor can now move \nfreely into the system, depending on his or her access privileges. These privileges \ncan also be escalated using any local exploits that match the system's environment, \nwhich, once executed, should help you attain super-user or system-level privileges. \nFrom this point of entry, an auditor might also be able to launch further attacks \nagainst the local network systems. This process can be restricted or non-restricted \ndepending on the given target's scope. There is also a possibility of learning more \nabout the compromised target by sniffing the network traffic, cracking passwords of \nvarious services, and applying local network spoofing tactics. Hence, the purpose of \nprivilege escalation is to gain the highest-level access to the system that is possible.\nMaintaining access\nSometimes, an auditor might be asked to retain access to the system for a specified \ntime period. Such activity can be used to demonstrate illegitimate access to the \nsystem without performing the penetration testing process again. This saves time, \ncost, and resources that are being served to gain access to the system for security \npurposes. Employing some secret tunneling methods, which make a use of protocol, \nproxy, or end-to-end connection strategy that can lead to establishing a backdoor \naccess, can help an auditor maintain his or her footsteps into the target system as \nlong as required. This kind of system access provides you with a clear view on how \nan attacker can maintain his or her presence in the system without noisy behavior.\nDocumentation and reporting\nDocumenting, reporting, and presenting the vulnerabilities found, verified, \nand exploited will conclude your penetration testing activities. From an ethical \nperspective, this is extremely important because the concerned managerial and \ntechnical team can inspect the method of penetration and try to close any security \nloopholes that may exist. The types of reports that are created for each relevant \nauthority in the contracting organization may have different outlooks to assist the \nbusiness and technical staff understand and analyze the weak points that exist in \ntheir IT infrastructure. Additionally, these reports can serve the purpose of capturing \nand comparing the target system's integrity before and after the penetration process.\n" }, { "page_number": 90, "text": "Chapter 2\n[ 69 ]\nThe ethics\nThe ethical vision of security testing constitutes rules of engagement that have to \nbe followed by an auditor to present professional, ethical, and authorized practices. \nThese rules define how the testing services should be offered, how the testing should \nbe performed, determine the legal contracts and negotiations, define the scope \nof testing, prepare the test plan, follow the test process, and manage a consistent \nreporting structure. Addressing each of these areas requires careful examination and \nthe design of formal practices and procedures must be followed throughout the test \nengagement. Some examples of these rules are discussed as follows:\n•\t\nOffering testing services after breaking into the target system before \nmaking any formal agreement between the client and auditor is completely \nforbidden. This act of unethical marketing can result in the failure of a \nbusiness and might have severe legal implications depending on the \njurisdictions of a country.\n•\t\nPerforming a test beyond the scope of testing and crossing the identified \nboundaries without explicit permissions from a client is prohibited.\n•\t\nBinding a legal contract that should limit the liability of a job unless any \nillegal activity is detected. The contract should clearly state the terms and \nconditions of testing, the emergency contact information, the statement of \nwork, and any obvious conflicts of interest.\n•\t\nThe test plan concerns the amount of time that is required to assess the \nsecurity of a target system. It is highly advisable to draw up a schedule that \ndoes not interrupt the production of business hours.\n•\t\nThe test process defines the set of steps that are required to be followed \nduring the test engagement. These rules combine technical and managerial \nviews to restrict the testing process with its environment and people.\n•\t\nScope definition should clearly define all the contractual entities and the \nlimits imposed on them during the security assessment.\n•\t\nTest results and reporting must be presented in a clear and consistent order. \nThe report must mark all the known and unknown vulnerabilities and \nshould be delivered confidentially to the authorized individual only.\n" }, { "page_number": 91, "text": "Penetration Testing Methodology\n[ 70 ]\nSummary\nIn this chapter, we have discussed several penetration testing methodologies. We \nhave also described the basic terminology of penetration testing, its associated types, \nand the industry contradiction with other similar terms. The summary of these key \npoints is highlighted as follows:\n•\t\nPenetration testing can be broken into different types such as black box and \nwhite box. The black box approach is also known as external testing, where \nthe auditor has no prior knowledge of the target system. The white box \napproach refers to an internal testing, where the auditor is fully aware of \ntarget environment. The combination of both types is known as a gray box.\n•\t\nThe basic difference between vulnerability assessment and penetration \ntesting is that the vulnerability assessments identify the flaws that exist in \nthe system without measuring their impact, while the penetration testing \ntakes a step forward and exploits these vulnerabilities in order to evaluate \ntheir consequences.\n•\t\nThere are a number of security testing methodologies but very few provide \nstepwise, consistent instructions on measuring the security of a system or \napplication. We have discussed five such well-known open source security \nassessment methodologies, highlighting their technical capabilities, key \nfeatures, and benefits. These include OSSTMM, ISSAF, OWASP, PTES, and \nWASC-TC.\n•\t\nWe also presented a simplified and structured testing framework for \npenetration testing. This process involves a number of steps, which have \nbeen organized according to the industry approach towards security testing. \nThese include target scoping, information gathering, target discovery, \nenumerating target, vulnerability mapping, social engineering, target \nexploitation, privilege escalation, maintaining access, and documentation \nand reporting.\n•\t\nFinally, we discussed the ethical view of penetration testing that should be \njustified and followed throughout the assessment process. Considering ethics \nduring every single step of assessment engagements leads to a successful \narrangement between auditor and business entity.\nThe next chapter will guide you through the strategic engagement of acquiring and \nmanaging information taken from the client for the penetration testing assignment.\n" }, { "page_number": 92, "text": "PART II\nPenetration \nTesters Armory\nTarget Scoping \nInformation Gathering\nTarget Discovery\nEnumerating Target\nVulnerability Mapping\nSocial Engineering\nTarget Exploitation\nPrivilege Escalation\nMaintaining Access\nDocumentation and Reporting\n" }, { "page_number": 93, "text": "" }, { "page_number": 94, "text": "Target Scoping\nTarget Scoping is defined as an empirical process to gather target assessment \nrequirements and characterize each of its parameters in order to generate a test \nplan, its limitations, business objectives, and time schedule. This process plays an \nimportant role in defining clear objectives towards any kind of security assessment. \nBy determining these key objectives, one can easily draw a practical road map of \nwhat will be tested, how it will be tested, what resources will be allocated, what \nlimitations will be applied, what business objectives will be achieved, and how the \ntest project will be planned and scheduled. Thus, we have combined all of these \nelements and presented them in a formalized scope process to achieve the required \ngoal. The following are the key concepts that will be discussed in this chapter:\n•\t\nGathering client requirements: This deals with accumulating information \nabout the target environment through verbal or written communication.\n•\t\nPreparing the test plan: This depends on different sets of variables. These \nvariables may include shaping the actual requirements into a structured \ntesting process, legal agreements, cost analysis, and resource allocation.\n•\t\nProfiling test boundaries: This determines the limitations associated with \nthe penetration testing assignment. These can be a limitation of technology, \nknowledge, or a formal restriction on the client's IT environment.\n•\t\nDefining business objectives: This is a process of aligning business views \nwith the technical objectives of the penetration testing program.\n•\t\nProject management and scheduling: This directs every other step of the \npenetration testing process with a proper timeline for test execution. This can \nbe achieved using a number of advanced project management tools.\n" }, { "page_number": 95, "text": "Target Scoping\n[ 74 ]\nIt is highly recommended that you follow the scope process in order to ensure \ntest consistency and a greater probability of success. Additionally, this process \ncan also be adjusted according to the given situation and test factors. Without any \nsuch process, there will be a greater chance of failure as the requirements gathered \nwill have no proper definitions and procedures to follow. This can lead the entire \npenetration testing project into danger and may result in an unexpected business \ninterruption. At this stage, paying special attention to the penetration testing process \nwould make an excellent contribution towards the rest of the test phases and clear \nthe perspectives of both technical and management areas. The key is to acquire as \nmuch information beforehand as possible from the client to formulate a strategic \npath that reflects the multiple aspects of penetration testing. These may include \nnegotiable legal terms, contractual agreement, resource allocation, test limitations, \ncore competencies, infrastructure information, timescales, and rules of engagement. \nAs a part of best practices, the scope process addresses each of the attributes that are \nnecessary to initiate our penetration testing project in a professional manner.\nEach step constitutes unique information that is aligned in a logical order to pursue \nthe test execution successfully. This also governs any legal matters to be resolved \nat an early stage. Hence, we will explain each of these steps in more detail in \nthe following section. Keep in mind that it will be easier for both the client and \npenetration testing consultant to further understand the process of testing if all the \ninformation gathered is managed in an organized manner.\nGathering client requirements\nThis step provides a generic guideline that can be drawn in the form of a \nquestionnaire to devise all the information about target infrastructure from a client. \nA client can be any subject who is legally and commercially bound to the target \norganization. Thus, for the success of the penetration testing project, it is critical \nto identify all internal and external stakeholders at an early stage of a project and \nanalyze their levels of interest, expectations, importance, and influence. A strategy \ncan then be developed to approach each stakeholder with their requirements \nand involvement in the penetration testing project in order to maximize positive \ninfluences and mitigate potential negative impacts. \nIt is solely the duty of the penetration tester to verify the identity of \nthe contracting party before taking any further steps. \n" }, { "page_number": 96, "text": "Chapter 3\n[ 75 ]\nThe basic purpose of gathering client requirements is to open a true and authentic \nchannel by which the pentester can obtain any information that may be necessary for \nthe testing process. Once the test requirements have been identified, the client should \nvalidate them in order to remove any misleading information. This will ensure that \nthe developed test plan is consistent and complete.\nCreating the customer requirements form\nWe have listed some of the commonly asked questions and considerations that \nmay be used as a basis to create a conventional customer requirements form. It is \nimportant to note that this list can be extended or shortened according to the goal \nof a client.\n•\t\nCollect basic information such as company name, address, website, contact \nperson(s) details, e-mail address, and telephone number(s).\n•\t\nDetermine the key objectives behind the penetration testing project.\n•\t\nDetermine the penetration test type (with or without specific criteria):\n°°\nBlack box testing\n°°\nWhite box testing\n°°\nExternal testing\n°°\nInternal testing\n°°\nSocial engineering included\n°°\nSocial engineering excluded\n°°\nInvestigate employee background information\n°°\nAdopt employee's fake identity (legal council may be required)\n°°\nDenial of service included\n°°\nDenial of service excluded\n°°\nPenetrate business partner systems\n•\t\nHow many servers, workstations, and network devices need to be tested?\n•\t\nWhich operating system technologies are supported by your infrastructure?\n•\t\nWhich network devices need to be tested? Firewalls, routers, switches, load \nbalancers, IDS, IPS, or any other appliances?\n•\t\nAre disaster recovery plans in place? If yes, whom should we contact?\n•\t\nAre there any administrators currently managing your network?\n•\t\nIs there any specific requirement to comply with industry standards? If yes, \nlist them.\n" }, { "page_number": 97, "text": "Target Scoping\n[ 76 ]\n•\t\nWho will be the point of contact for this project?\n•\t\nWhat is the timeline allocated for this project? \n•\t\nWhat is your budget for this project?\n•\t\nList any miscellaneous requirements, if necessary.\nThe deliverables assessment form\nThe following is an example of the type of items expected from a deliverables \nassessment form. This list is not holistic and items should be added or removed \nbased on customer expectations and needs:\n•\t\nWhat types of reports are expected?\n°°\nExecutive reports\n°°\nTechnical assessment reports\n°°\nDeveloper reports\n•\t\nIn which format do you prefer the report to be delivered? PDF, HTML, \nor DOC.\n•\t\nHow should the report be submitted? Encrypted e-mail or printed?\n•\t\nWho is responsible for receiving these reports?\n°°\nEmployee\n°°\nShareholder\n°°\nStakeholder\nBy using such a concise and comprehensive inquiry form, you can easily extract the \ncustomer requirements and fulfill the test plan accordingly.\nPreparing the test plan\nAs the requirements have been gathered and verified by a client, it is time to draw \na formal test plan that should reflect all of these requirements, in addition to other \nnecessary information on the legal and commercial grounds of the testing process. \nThe key variables involved in preparing a test plan are structured testing process, \nresource allocation, cost analysis, non-disclosure agreement, penetration testing \ncontract, and rules of engagement. Each of these areas is addressed with their short \ndescriptions as follows:\n" }, { "page_number": 98, "text": "Chapter 3\n[ 77 ]\n•\t\nStructured testing process: After analyzing the details provided by your \ncustomer, it may be important to restructure your testing methodology. \nFor instance, if the social engineering service is about to be excluded, you \nwould have to remove it from the formal testing process. Sometimes, this \npractice is known as test process validation. It is a repetitive task that has \nto be revisited whenever there is a change in client requirements. If there \nare any unnecessary steps involved during the test execution, it may result \nin a violation of the organization's policies and incur serious penalties. \nAdditionally, based on the test type, there would be a number of changes \nto the test process. As an example, white box testing may not require the \ninformation gathering and target discovery phases, because the tester is \nalready aware of the internal infrastructure. \nThe validation of the network and environment data may \nbe useful regardless of the test type. After all, the client \nmay not know what their network really looks like!\n•\t\nResource allocation: Determining the expertise knowledge required to \nachieve the completeness of a test is one of the substantial areas. Thus, \nassigning an appropriately skilled penetration tester to a certain task may \nresult in better security assessment. For instance, an application penetration \ntesting requires a knowledgeable application security tester. This activity \nplays a significant role in the success of the penetration testing assignment.\n•\t\nCost analysis: The cost for penetration testing depends on several factors. \nThis may involve the number of days allocated to fulfill the scope of a \nproject, additional service requirements such as social engineering and \nphysical security assessment, and the expertise knowledge required to assess \nthe specific technology. From an industry viewpoint, this should combine a \nqualitative and quantitative value.\n•\t\nNon-disclosure Agreement (NDA): Before starting the test process, it is \nnecessary to sign an NDA agreement that will reflect the interests of both \nparties: the client and penetration tester. Using such a mutual non-disclosure \nagreement should clear the terms and conditions under which the test \nshould be aligned. The penetration tester should comply with these terms \nthroughout the test process. Violating any single term of agreement can \nresult in serious penalties or permanent exemption from the job.\n" }, { "page_number": 99, "text": "Target Scoping\n[ 78 ]\n•\t\nPenetration testing contract: There is always the need for a legal contract \nthat will address the technical and business matters between the client and \npenetration tester. This is where the penetration testing contract comes in. \nThe basic information in such contracts focuses on what testing services are \nbeing offered, their main objectives, how they will be conducted, payment \ndeclaration, and maintaining the confidentiality of the whole project. It is \nhighly recommended that you have this document created by an attorney or \nlegal counsel, as it will be used for most of your penetration testing activities.\n•\t\nRules of engagement (ROE): The process of penetration testing can be \ninvasive and requires a clear understanding of the assessment's demands, \nsupport provided by the client, and type of potential impact or effect each \nassessment technique may have. Moreover, the tools used in the penetration \ntesting processes should clearly state their purpose so that the tester can use \nthem accordingly. The rules of engagement define all of these statements in \na more detailed fashion to address the necessity of the technical criteria that \nshould be followed during the test execution. You should never cross the \nboundaries set within the pre-agreed upon ROE. \nBy preparing each of these subparts of the test plan, you can ensure that you have \na consistent view of the penetration testing process. This will provide a penetration \ntester with more specific assessment details that have been processed from the client \nrequirements. It is always recommended that you prepare a test plan checklist, \nwhich can be used to verify the assessment criteria and its underlying terms with \nthe contracting party. One of such exemplary types of checklist is discussed in the \nfollowing section.\nThe test plan checklist\nThe following is an example of a set of questions that should be answered correctly \nbefore taking any further steps in the scope process:\n•\t\nAre all the requirements promised during the RFP being met?\n•\t\nIs the test scope defined clearly?\n•\t\nHave all the testing entities been identified?\n•\t\nHave all the non-testing entities been separately listed?\n•\t\nIs there any specific testing process that will be followed?\n•\t\nIs the testing process documented correctly?\n•\t\nWill the deliverables be produced upon the completion of a test process?\n•\t\nHas the entire target environment been researched and documented before?\n•\t\nHave all the roles and responsibilities been assigned for the testing activities?\n" }, { "page_number": 100, "text": "Chapter 3\n[ 79 ]\n•\t\nIs there any third-party contractor to accomplish technology-specific \nassessment?\n•\t\nHave any steps been taken to bring the project to a graceful closure?\n•\t\nHas the disaster recovery plan been identified?\n•\t\nHas the cost of the test project been finalized?\n•\t\nHave the people who will approve the test plan been identified?\n•\t\nHave the people who will accept the test results been identified?\nProfiling test boundaries\nUnderstanding the limitations and boundaries of the test environment goes hand \nin hand with the client requirements, which can be justified as intentional or \nunintentional interests. These can be in the form of technology, knowledge, or any \nother formal restrictions imposed by the client on the infrastructure. Each limitation \nimposed may cause a serious interruption to the testing process and can be resolved \nusing alternative methods. However, note that certain restrictions cannot be \nmodified as they are administered by the client to control the process of penetration \ntesting. We will discuss each of these generic types of limitations with their relevant \nexamples as follows:\n•\t\nTechnology limitations: This type of limitation occurs when the scope of \na project is properly defined but the presence of a new technology in the \nnetwork infrastructure does not let the auditor test it. This happens only \nwhen the auditor does not have any pen-testing tool that can assist in \nthe assessment of this new technology. For instance, a company XYZ has \nintroduced a robust GZ network firewall device that sits at the perimeter and \nworks to protect the entire internal network. However, its implementation of \nproprietary methods inside the firewall does not let any firewall assessment \ntool work. Thus, there is always a need for an up-to-date solution that can \nhandle the assessment of such a new technology.\n•\t\nKnowledge limitations: The knowledge limitations of a pentester can \nhave a negative impact if their skill level is narrow and he or she is not \ncapable of testing certain technologies. For example, a dedicated database \npenetration tester would not be able to assess the physical security \nof a network infrastructure. Hence, it is good to divide the roles and \nresponsibilities according to the skills and knowledge of the pentester to \nachieve the required goal.\n" }, { "page_number": 101, "text": "Target Scoping\n[ 80 ]\n•\t\nOther infrastructure restrictions: Certain test restrictions can be applied by \nthe client to control the assessment process. This can be done by limiting the \nview of an IT infrastructure to only specific network devices and technologies \nthat need assessment. Generally, this kind of restriction is introduced during \nthe requirement gathering phase. For instance, test all the devices behind the \nnetwork segment A except the first router. Restrictions that are imposed by \nthe client do not ensure the security of a router in the first place, which can \nlead to a compromise in the whole network, even if all the other network \ndevices are hardened and security-assured. Thus, proper thinking is always \nrequired before putting any such restrictions on the penetration testing.\nProfiling all of these limitations and restrictions is important, which can be observed \nwhile gathering the client requirements. A good pentester's duty is to dissect each \nrequirement and hold a discussion with the client to pull or change any ambiguous \nrestrictions that may cause an interruption to the testing process or result in a \nsecurity breach in the near future. These limitations can also be overcome by \nintroducing highly skilled pen-testers and an advanced set of tools and techniques \nfor the assessment. Although by nature, certain technology limitations cannot be \neliminated, and you may require extra time to develop their testing solutions.\nDefining business objectives\nBased on the assessment requirements and the endorsement of services, it is vital \nto define the business objectives. This will ensure that the testing output benefits \na business from multiple aspects. Each of these business objectives is focused and \nstructured according to the assessment requirements and can provide a clear view of \nthe industry achievement. We have formatted some general business objectives that \ncan be used to align with any penetration testing assignment. However, they can also \nbe redesigned according to the change in requirements. This process is important \nand may require a pentester to observe and understand the business motives while \nmaintaining the minimum level of standard before, during, and after the test is \ncompleted. Business objectives are the main source to bring the management and \ntechnical team together in order to support a strong proposition and an idea of \nsecuring information systems. Based on the different kinds of security assessments to \nbe carried out, the following list of common objectives has been derived:\n•\t\nProvide industry-wide visibility and acceptance by maintaining regular \nsecurity checks.\n•\t\nAchieve the necessary standards and compliance by assuring \nbusiness integrity.\n•\t\nSecure the information systems holding confidential data about the \ncustomers, employees, and other business entities.\n" }, { "page_number": 102, "text": "Chapter 3\n[ 81 ]\n•\t\nList the active threats and vulnerabilities found in the network infrastructure, \nand help to create security policies and procedures that should thwart known \nand unknown risks.\n•\t\nProvide a smooth and robust business structure that will benefit its partners \nand clients.\n•\t\nRetain the minimum cost for maintaining the security of an IT infrastructure. \nThe security assessment measures the confidentiality, integrity, and \navailability of the business systems.\n•\t\nProvide greater return on investment by eliminating any potential risks that \nmight cost more if exploited by a malicious adversary.\n•\t\nDetail the remediation procedures that can be followed by a technical team \nat the concerning organization to close any open doors, and thus, reduce the \noperational burden.\n•\t\nFollow the industry best practices and best-of-breed tools and techniques to \nevaluate the security of the information systems according to the underlying \ntechnology.\n•\t\nRecommend any possible security solutions that should be used to protect \nthe business assets.\nProject management and scheduling\nManaging the penetration testing project requires a thorough understanding of all the \nindividual parts of the scoping process. Once these scope objectives have been cleared, \nthe project manager can coordinate with the penetration testers to develop a formal \noutline that defines the project plan and schedule. Usually, the penetration tester can \ncarry out this task unaided, but the cooperation of a client could possibly bring positive \nattention to that part of the schedule. This is important because test execution requires \ncareful allotment of the timescale that should not exceed the declared deadline. Once \nthe proper resources have been identified and allocated to perform certain tasks \nduring the assessment period, it becomes necessary to draw a timeline depicting those \nresources with their key parts in the penetration testing process.\nEach task is defined as a piece of work undertaken by the penetration tester. The \nresource can be a person involved in the security assessment or an ordinary source \nsuch as lab equipment, which can be helpful in penetration testing. In order to \nmanage these projects efficiently and cost effectively, there are a number project \nmanagement tools available that can be used to achieve our mission. We have listed \nsome important project management tools in the following table. Selecting the best \none depends on the environment and requirements of the testing criteria.\n" }, { "page_number": 103, "text": "Target Scoping\n[ 82 ]\nProject management tools\nWebsites\nMicrosoft Office Project Professional\nhttp://www.microsoft.com/project/\nTimeControl\nhttp://www.timecontrol.com/\nTaskMerlin\nhttp://www.taskmerlin.com/\nProject KickStart Pro\nhttp://www.projectkickstart.com/\nFastTrack Schedule\nhttp://www.aecsoftware.com/\nSerena OpenProj\nhttp://www.openproj.org/\nTaskJuggler\nhttp://www.taskjuggler.org/\nUsing any of these powerful tools, the work of the penetration tester can be easily \ntracked and managed in accordance with their defined tasks and time period. \nAdditionally, these tools provide the most advanced features, such as generating \nan alert for the project manager if the task has been finished or the deadline has \nbeen crossed. There are many other positive facts that encourage the use of project \nmanagement tools during the penetration testing assignment. These include \nefficiency in delivering services on time, improved test productivity and customer \nsatisfaction, increased quality and quantity of work, and flexibility to control the \nwork progress.\nSummary\nThis chapter explains the target scoping aspect of penetration testing. If you are \nplanning on performing professional penetration testing, this step should be high \non your list of priorities. The main objective of this chapter is to provide a necessary \nguideline on formalizing the test requirements. For this purpose, a scope process \nhas been introduced to highlight and describe each factor that builds a practical \nroadmap towards the test execution. The scope process comprises five independent \nelements, which are gathering client requirements, preparing test plan, profiling test \nboundaries, defining business objectives, and project management and scheduling. \nThe aim of a scope process is to acquire and manage as much information as possible \nabout the target environment, which can be useful throughout the penetration \ntesting process. As discussed in the chapter, we have summarized each part of the \nscope processes in the following manner:\n•\t\nGathering client requirements provides a practical guideline on what \ninformation should be gathered from a client or customer in order to conduct \nthe penetration testing successfully. Covering the data on the types of \npenetration testing, infrastructure information, organization profile, budget \noutlook, time allocation, and type of deliverables are some of the most \nimportant areas that should be cleared at this stage.\n" }, { "page_number": 104, "text": "Chapter 3\n[ 83 ]\n•\t\nPreparing a test plan combines structured testing process, resource \nallocation, cost analysis, non-disclosure agreement, penetration testing \ncontract, and rules of engagement. All these branches constitute a step-by-\nstep process to prepare a formal test plan that should reflect the actual client \nrequirements, legal and commercial prospects, resource and cost data, and \nthe rules of engagement. Additionally, we have also provided an exemplary \ntype of checklist that can be used to ensure the integrity of a test plan.\n•\t\nProfiling test boundaries provides a guideline on what type of limitations \nand restrictions may occur while justifying the client requirements. These \ncan be in the form of technology limitations, knowledge limitations, or \nother infrastructure restrictions posed by the client to control the process of \npenetration testing. These test boundaries can be clearly identified from the \nclient requirements. There are certain procedures that can be followed to \novercome these limitations.\n•\t\nDefining business objectives focuses on key benefits that a client may \nget from the penetration testing service. This section provides a set of \ngeneral objectives structured according to the assessment criteria and the \nindustry achievement.\n•\t\nProject management and scheduling is a vital part of a scope process. Once \nall the requirements have been gathered and aligned according to the test \nplan, it's time to allocate proper resources and timescale for each identified \ntask. By using some advanced project management tools, one can easily keep \na track of all these tasks assigned to specific resources under the defined \ntimeline. This can help increase the test productivity and efficiency.\nIn the next chapter, we will illustrate the practical reconnaissance process that \ncontributes a key role in penetration testing. This includes probing the public \nresources, DNS servers, search engines, and other logical information on target \ninfrastructure.\n" }, { "page_number": 105, "text": "" }, { "page_number": 106, "text": "Information Gathering\nIn this chapter, we will discuss the information gathering phase of penetration \ntesting. We will describe the definition and purpose of information gathering. \nWe will also describe several tools in Kali Linux that can be used for information \ngathering. After reading this chapter, we hope that the reader will have a better \nunderstanding of the information gathering phase and will be able to do information \ngathering during penetration testing.\nInformation gathering is the second phase in our penetration testing process (Kali \nLinux testing process) as explained in the Kali Linux testing methodology section in \nChapter 2, Penetration Testing Methodology. In this phase, we try to collect as much \ninformation as we can about the target, for example, information about the Domain \nName System (DNS) hostnames, IP addresses, technologies and configuration used, \nusername's organization, documents, application code, password reset information, \ncontact information, and so on. During information gathering, every piece of \ninformation gathered is considered important.\nInformation gathering can be categorized in two ways based on the method used: \nactive information gathering and passive information gathering. In the active \ninformation gathering method, we collect information by introducing network traffic \nto the target network. While, in the passive information gathering method, we gather \ninformation about a target network by utilizing a third-party's services, such as the \nGoogle search engine. We will cover this later on.\nRemember that no method is better in comparison to the other; each \nhas its own advantage. In passive scanning, you gather less information \nbut your action will be stealthy; while, in active scanning, you get \nmore information but some devices may catch your action. During a \npenetration testing project, this phase may be done several times for the \ncompleteness of information collected. You may also discuss with your \npen-testing customer, which method they want.\n" }, { "page_number": 107, "text": "Information Gathering\n[ 86 ]\nFor this chapter, we will utilize the passive and active methods of information \ngathering to get a better picture of the target.\nWe will discuss the following topics in this chapter:\n•\t\nPublic websites that can be used to collect information about the target \ndomain\n•\t\nDomain registration information\n•\t\nDNS analysis\n•\t\nRoute information\n•\t\nSearch engine utilization\nUsing public resources\nOn the Internet, there are several public resources that can be used to collect \ninformation regarding a target domain. The benefit of using these resources is that \nyour network traffic is not sent to the target domain directly, so our activities are not \nrecorded in the target domain logfiles.\nThe following are the resources that can be used:\nNo.\nResource URL\nDescription\n1\nhttp://www.archive.org\nThis contains an archive of websites.\n2\nhttp://www.domaintools.com/\nThis contains domain name intelligence.\n3\nhttp://www.alexa.com/\nThis contains the database of information \nabout websites.\n4\nhttp://serversniff.net/\nThis is the free \"Swiss Army Knife\" for \nnetworking, server checks, and routing.\n5\nhttp://centralops.net/\nThis contains free online network utilities \nsuch as domain, e-mail, browser, ping, \ntraceroute, and Whois. \n6\nhttp://www.robtex.com\nThis allows you to search for domain and \nnetwork information.\n7\nhttp://www.pipl.com/\nThis allows you to search for people on the \nInternet by their first and last names, city, \nstate, and country.\n8\nhttp://yoname.com\nThis allows you to search for people across \nsocial networking sites and blogs.\n9\nhttp://wink.com/\nThis is a free search engine that allows you \nto find people by their name, phone number, \ne-mail, website, photo, and so on.\n" }, { "page_number": 108, "text": "Chapter 4\n[ 87 ]\nNo.\nResource URL\nDescription\n10\nhttp://www.isearch.com/\nThis is a free search engine that allows you \nto find people by their name, phone number, \nand e-mail address.\n11\nhttp://www.tineye.com\nTinEye is a reverse image search engine. We \ncan use TinEye to find out where the image \ncame from, how it is being used, whether \nmodified versions of the image exist, or to \nfind higher resolution versions.\n12\nhttp://www.sec.gov/edgar.\nshtml\nThis can be used to search for information \nregarding public listed companies in the \nSecurities and Exchange Commission.\nDue to the ease of use, you only need an Internet connection and a web browser, we \nsuggest that you utilize these public resources first before using the tools provided \nwith Kali Linux.\nTo protect a domain from being abused, we have changed the domain \nname that we used in our examples. We are going to use several \ndomain names, such as example.com from IANA and a dummy \ndomain name example.com as well for illustrative purposes.\nQuerying the domain registration \ninformation\nAfter you know the target domain name, the first thing you would want to do is \nquery the Whois database about that domain to look for the domain registration \ninformation. The Whois database will give information about the DNS server and the \ncontact information of a domain.\nWHOIS is a protocol for searching Internet registrations, databases for registered \ndomain names, IPs, and autonomous systems. This protocol is specified in RFC 3912 \n(https://www.ietf.org/rfc/rfc3912.txt).\nBy default, Kali Linux already comes with a whois client. To find out the Whois \ninformation for a domain, just type the following command:\n# whois example.com\n" }, { "page_number": 109, "text": "Information Gathering\n[ 88 ]\nThe following is the abridged result of the Whois information:\nWhois Server Version 2.0\nDomain names in the .com and .net domains can now be registered\nwith many different competing registrars. Go to http://www.internic.\nnet\nfor detailed information.\n Domain Name: EXAMPLE.COM\n Registrar: REGISTRAR.COM\n Whois Server: whois.registrar.com\n Referral URL: http://registrar.com\n Name Server: NS.HOSTING.COM\n Name Server: NS2.HOSTING.COM\n Status: clientDeleteProhibited\n Status: clientRenewProhibited\n Status: clientTransferProhibited\n Status: clientUpdateProhibited\n Updated Date: 08-apr-2012\n Creation Date: 08-apr-2012\n Expiration Date: 08-apr-2015\n>>> Last update of whois database: Wed, 25 Jul 2012 02:15:41 UTC <<<\nPlease note: the registrant of the domain name is specified\nin the \"registrant\" field. In most cases, registrar.com \nis not the registrant of domain names listed in this database.\nThe Registrant:\n Jalan Sudirman No. 1\n DKI Jakarta\n Indonesia 12345\n Domain Name: EXAMPLE.COM\n Created on: 08-Apr-12\n Expires on: 08-Apr-15\n Last Updated on: 08-Apr-12\n Administrative Contact:\n The Registrant\n Jalan Sudirman No. 1\n DKI Jakarta\n Indonesia 12345\n 62 2112345678\n" }, { "page_number": 110, "text": "Chapter 4\n[ 89 ]\n Technical Contact:\n The Registrant registrant@example.com\n Jalan Sudirman No. 1\n DKI Jakarta\n Indonesia 12345\n 62 2112345678\n Domain servers in listed order:\n NS.HOSTING.COM\n NS2.HOSTING.COM\nFrom the preceding Whois result, we can get the information of the DNS server and \nthe contact person of a domain. This information will be useful at the later stages of \npenetration testing.\nBesides using the command-line whois client, the Whois information can also be \ncollected via the following websites, which provide the whois client:\n•\t\nwww.whois.net\n•\t\nwww.internic.net/whois.html\nOr, you can also go to the top-level domain registrar for the corresponding domain:\n•\t\nAmerica: www.arin.net/whois/\n•\t\nEurope: www.db.ripe.net/whois\n•\t\nAsia-Pacific: www.apnic.net/apnic-info/whois_search2\nBeware, that to use the top-level domain registrar whois, the domain \nneeds to be registered through their own system. For example, if you use \nARIN WHOIS, it only searches in the ARIN WHOIS database and will not \nsearch in the RIPE and APNIC Whois databases.\nAfter getting information from the Whois database, next we want to gather \ninformation about the DNS entries of the target domain.\nAnalyzing the DNS records\nThe goal of using the tools in the DNS records category is to collect information \nabout the DNS servers and the corresponding records of a target domain.\n" }, { "page_number": 111, "text": "Information Gathering\n[ 90 ]\nThe following are several common DNS record types:\nNo.\nRecord type\nDescription\n1\nSOA\nThis is the start of authority record.\n2\nNS\nThis is the name server record.\n3\nA\nThis is the IPv4 address record.\n4\nMX\nThis is the mail exchange record.\n5\nPTR\nThis is the pointer record. \n6\nAAAA\nThis is the IPv6 address record.\n7\nCNAME\nThis is the abbreviation for canonical name. It is used as an alias \nname for another canonical domain name.\nFor example, in a penetration test engagement, the customer may ask you to find out \nall of the hosts and IP addresses available for their domain. The only information \nyou have is the organization's domain name. We will look at several common tools \nthat can help you if you encounter this situation.\nhost\nAfter we get the DNS server information, the next step is to find out the IP address of \na hostname. To help us out on this matter, we can use the following host command-\nline tool to lookup the IP address of a host from a DNS server:\n# host www.example.com\nThe following is the command's result:\nwww.example.com has address 192.0.43.10\nwww.example.com has IPv6 address 2001:500:88:200::10\nLooking at the result, we know the IPv4 and IPv6 addresses of the host www.\nexample.com.\nBy default, the host command will look for the A, AAAA, and MX records of a domain. \nTo query for any records, just give the -a option to the command.\n# host -a example.com\nTrying \"example.com\"\n;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 25153\n;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 2\n;; QUESTION SECTION:\n;example.com. IN ANY\n" }, { "page_number": 112, "text": "Chapter 4\n[ 91 ]\n;; ANSWER SECTION:\nexample.com. 3201 IN SOA dns1.icann.org. \nhostmaster.icann.org. 2012080782 7200 3600 1209600 3600\nexample.com. 46840 IN NS a.iana-servers.net.\nexample.com. 46840 IN NS b.iana-servers.net.\n;; ADDITIONAL SECTION:\nb.iana-servers.net. 1401 IN A 199.43.133.53\na.iana-servers.net. 1401 IN A 199.43.132.53\nReceived 170 bytes from 202.152.165.39#53 in 563 ms\nThe host command looks for these records by querying the DNS servers listed in \nthe /etc/resolv.conf file of your Kali Linux system. If you want to use other DNS \nservers, just give the DNS server address as the last command-line option.\nIf you give the domain name as the command-line option in host, \nthe method is called forward lookup, but if you give an IP address as \nthe command-line option to the host command, the method is called \nreverse lookup.\nTry to do a reverse lookup of the following IP address:\nhost 23.23.144.81\nWhat information can you get from this command?\nThe host tool can also be used to do a DNS zone transfer. With this mechanism, we \ncan collect information about the available hostnames in a domain.\nA DNS zone transfer is a mechanism used to replicate a DNS \ndatabase from a master DNS server to another DNS server, \nusually called a slave DNS server. Without this mechanism, the \nadministrators have to update each DNS server separately. The DNS \nzone transfer query must be issued to an authoritative DNS server of \na domain.\nDue to the nature of information that can be gathered by a DNS zone \ntransfer, nowadays, it is very rare to find a DNS server that allows \nzone transfer to an arbitrary zone transfer request.\nIf you find a DNS server that allows zone transfer without limiting \nwho is able to do it, this means that the DNS server has been \nconfigured incorrectly.\n" }, { "page_number": 113, "text": "Information Gathering\n[ 92 ]\nThe following is an example of performing DNS zone transfer for a domain via a \nmisconfigured DNS server:\n# host -l example.com ns4.isp.com\nThe following is the DNS zone transfer result:\nUsing domain server:\nName: ns4.isp.com\nAddress: 172.16.176.22#53\nAliases: \nexample.com name server ns1.isp.com.\nexample.com name server ns2.isp.com.\nexample.com has address 192.168.1.1\nsmtp.example.com has address 192.168.1.2\nmail.example.com has address 192.168.1.3\nwebmail.example.com has address 192.168.1.3\nwww.example.com has address 192.168.1.4\nThe host command will return information about the NS, PTR, and address records \nof a domain. In this case, the misconfigured DNS server is ns4.isp.com.\ndig\nBesides the host command, you can also use the dig command to do DNS \ninterrogation. The advantages of dig compared to host are its flexibility and clarity \nof output. With dig, you can ask the system to process a list of lookup requests from \na file.\nLet's use dig to interrogate the example.com domain:\n" }, { "page_number": 114, "text": "Chapter 4\n[ 93 ]\nWithout giving any options besides the domain name, the dig command will only \nreturn the A record of a domain. To request for any other DNS record type, we can \ngive the type option in the command line:\n# dig example.com any\n; <<>> DiG 9.7.0-P1 <<>> example.com any\n;; global options: +cmd\n;; Got answer:\n;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 40971\n;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 2\n;; QUESTION SECTION:\n;example.com. IN ANY\n;; ANSWER SECTION:\nexample.com. 3565 IN SOA dns1.icann.org. \nhostmaster.icann.org. 2012080782 7200 3600 1209600 3600\nexample.com. 83186 IN AAAA 2001:500:88:200::10\nexample.com. 48296 IN NS b.iana-servers.net.\nexample.com. 48296 IN NS a.iana-servers.net.\n;; ADDITIONAL SECTION:\na.iana-servers.net. 182 IN A 199.43.132.53\nb.iana-servers.net. 182 IN A 199.43.133.53\n;; Query time: 327 msec\n;; SERVER: 202.152.165.39#53(202.152.165.39)\n;; WHEN: Sat Aug 18 10:46:09 2012\n;; MSG SIZE rcvd: 198\nFrom the result, we can see that the dig output now returns the DNS records of SOA, \nNS, A, and AAAA.\nTo do zone transfer using dig, we must set the authoritative DNS server for that \ndomain and set axfr as the type:\n# dig @ns4.isp.com example.com axfr\nFollowing is the abridged result of the preceding command:\n; <<>> DiG 9.7.0-P1 <<>> @ns4.isp.com example.com axfr\n; (1 server found)\n;; global options: +cmd\nexample.com. 3600 IN SOA ns1.isp.com. hostmaster.\nisp.com. 2011020409 900 600 86400 3600\n" }, { "page_number": 115, "text": "Information Gathering\n[ 94 ]\nexample.com. 3600 IN NS ns1.isp.com.\nexample.com. 3600 IN NS ns4.isp.com.\nexample.com. 3600 IN A 192.168.1.1\nexample.com. 3600 IN MX 192.168.1.3 \nmail.example.com. 3600 IN A 192.168.1.3\nwebmail.example.com. 3600 IN A 192.168.1.3\nwww.example.com. 3600 IN A 192.168.1.4\nexample.com. 3600 IN SOA ns1.isp.com. hostmaster.\nisp.com. 2011020409 900 600 86400 3600\n;; Query time: 855 msec\n;; SERVER: 172.16.176.22#53 (172.16.176.22)\n;; WHEN: Sat Aug 18 10:59:11 2012\n;; XFR size: 9 records\nWe can see in the preceding result that the DNS records are similar to those of the \nhost command. Based on this, we can be confident about the DNS records collected.\ndnsenum\nTo collect information from a DNS server, we can utilize dnsenum. The DNS \ninformation that can be gathered is as follows:\n•\t\nThe host IP addresses\n•\t\nThe DNS server of a domain\n•\t\nThe MX record of a domain\nIn this chapter, you may see that we used several tools that generate \nsimilar results, this is because we need to validate the information \ncollected. If the information is found in more than one tool, we can be \nmore confident with the information.\nBesides being used to get DNS information, dnsenum also has the following features:\n•\t\nGet additional names and subdomains utilizing the Google search engine.\n•\t\nFind out subdomain names by brute forcing the names from the text files. \nThe dnsenum tool included in Kali Linux comes with a dns.txt dictionary \nfile that contains 1,480 subdomain names and a dns-big.txt file, which \ncontains 266,930 subdomain names.\n•\t\nCarry out Whois queries on C-class domain network ranges and calculate its \nnetwork ranges.\n•\t\nCarry out reverse lookup on network ranges.\n•\t\nUse threads to process different queries.\n" }, { "page_number": 116, "text": "Chapter 4\n[ 95 ]\nTo access dnsenum, go to the console and type the following command:\n# dnsenum\nThis will display the usage instruction on your screen.\nAs an example of the dnsenum tool usage, we will use dnsenum to get DNS \ninformation from a target domain. The command to do this is as follows:\n# dnsenum example.com\nThe following is the abridged result of that command:\ndnsenum.pl example.com\ndnsenum.pl VERSION:1.2.2\n----- example.com -----\nHost's addresses:\n__________________\nName Servers:\n______________\nns1.isp.com 10771 IN A 172.168.1.2\nns0.isp.com 7141 IN A 172.168.1.1\nMail (MX) Servers:\n___________________\nhermes1.example.com 86400 IN A 192.168.10.3\nhermes.example.com 3600 IN A 192.168.10.2\nTrying Zone Transfers and getting Bind Versions:\n_________________________________________________\nTrying Zone Transfer for example.com on ns0.isp.com ... \nAXFR record query failed: NOERROR\nns0.isp.com Bind Version: \nDNS server\n" }, { "page_number": 117, "text": "Information Gathering\n[ 96 ]\nTrying Zone Transfer for example.com on ns1.isp.com ... \nexample.com 86400 IN SOA \nexample.com 86400 IN NS \nexample.com 86400 IN MX \nexample.com 86400 IN TXT \nadmin.example.com 3600 IN NS \nblogs.example.com 3600 IN NS \nftp.example.com \t 3600 IN A 192.168.10.4\nhermes.example.com 3600 IN A 192.168.10.2\nhermes.example.com \t\n86400 IN TXT \nhermes.example.com \t\n86400 IN SPF \nhermes1.example.com \t 86400 IN A 192.168.10.2\nwww.example.com \t 3600 IN NS \nns1.isp.com Bind Version: \nDNS server\nbrute force file not specified, bay.\nUsing the default options of dnsenum, we can get information about the host address, \nname servers, and the mail server's IP address. Fortunately, the ns1.isp.com DNS \nserver allows us to do zone transfer for the example.com domain.\nIn the case that the zone transfer is not successful, we can do brute forcing of the \nlookups to find the subdomains from a wordlist. For example, if we want to brute \nforce the subdomain using the provided text file wordlist (dns.txt), the following is \nthe appropriate command:\n dnsenum -f dns.txt example.com\nThe following is the result of the brute forcing process:\nBrute forcing with dns.txt: \n____________________________ \n \napps.example.com 86400 IN A 192.168.10.152 \nmail.example.com 86400 IN A 192.168.10.107\nportal.example.com 86400 IN A 192.168.10.249\nBeware that brute forcing the DNS lookups will take some time to finish.\nLuckily for us, the target domain uses common subdomain names. So we are able to \nfind several subdomains (apps, mail, and portal) in the target domain based on the \ndictionary file we have.\n" }, { "page_number": 118, "text": "Chapter 4\n[ 97 ]\nAnother technique that can be used to find the subdomain is by using Google. \nThis will be useful if the DNS zone transfer is disabled. To use Google, just add \nthe options -p for the number of Google pages to be processed or -s to define the \nnumber of subdomains to be collected. You may also want to set the number of \nthreads to do the queries (--threads) in order to speed up the process.\ndnsdict6\nUp until now, we only talked about the DNS tools to enumerate the subdomains in \nIP Version 4. If you want to enumerate the IP Version 6 subdomains, you can use \ndnsdict6 from the The Hacker's Choice (THC) group.\nTo access dnsdict6 in Kali Linux, you can use the console and type the following \ncommand:\n# dnsdict6\nIt will display the dsndict6 help page.\nWithout giving any options, dnsdict6 will use the built-in wordlist and eight \nthreads.\nLet's enumerate the subdomains available in the example.com domain using the \nfollowing command line:\n# dnsdict6 example.com\nThe following screenshot shows the result of this command:\nAfter brute forcing the subdomain using the dnsdict6 built-in wordlist (containing \n798 words), we know that there is only one subdomain (www) available in the \nexample.com domain that has an IP Version 6 address.\nWe found that the number of words displayed by dnsdict6 is \nincorrect. We tested this using a file containing three words; the \ndnsdict6 command informed us that the number of words is four.\n" }, { "page_number": 119, "text": "Information Gathering\n[ 98 ]\nAlso, the dnsdict6 tool can be used to find the subdomain on IP Version 4 using the \n-4, option, and it can also collect information about the DNS and NS of a domain by \nusing the -d option. Let's use these options to check the example.com domain:\nfierce\nThe fierce tool is a DNS enumeration tool that uses several techniques to find all \nof the IP addresses and hostnames of a target. It works by first querying your \nsystem's DNS server for the target DNS server; next, it uses the target DNS server. It \nalso supports the wordlist supplied by the user to find subdomain names. It does this \nrecursively until all of the wordlist items are tested. The main feature of fierce is \nthat it can be used to locate noncontiguous IP space and hostnames \nagainst specified domains.\nTo access fierce in Kali Linux, you can use the console and type the following \ncommand:\n# fierce -h\nThis will display the usage instructions on your screen.\nAs an example, let's use fierce to find information about a domain:\n# fierce -dns example.com -threads 3\nThe following is the abridged result:\nDNS Servers for targetdomain.com:\n ns4.example.com\n ns1.example.com\n ns2.example.com\n" }, { "page_number": 120, "text": "Chapter 4\n[ 99 ]\n ns3.example.com\nTrying zone transfer first...\n Testing ns4.example.com\n Request timed out or transfer not allowed.\n Testing ns1.example.com\n Request timed out or transfer not allowed.\n Testing ns2.example.com\n Request timed out or transfer not allowed.\n Testing ns3.example.com\n Request timed out or transfer not allowed.\nUnsuccessful in zone transfer (it was worth a shot)\nOkay, trying the good old fashioned way... brute force\nChecking for wildcard DNS...\nNope. Good.\nNow performing 1895 test(s)...\n192.168.116.3 voips.example.com\n192.168.116.7 ns.example.com\n192.168.116.19 streaming.example.com\n192.168.117.50 dev.example.com\n192.168.117.16 mx1.example.com\n192.168.117.17 mx2.example.com\n192.168.117.18 mx3.example.com\n192.168.117.16 imap.example.com\n192.168.117.5 www.example.com\n192.168.117.6 intra.example.com\n192.168.117.17 mail.example.com\n192.168.117.5 web.example.com\n192.168.117.16 webmail.example.com\nSubnets found (may want to probe here using nmap or unicornscan):\n 192.168.73.0-255 : 2 hostnames found.\n 192.168.46.0-255 : 1 hostnames found.\n 192.168.116.0-255 : 34 hostnames found.\n 192.168.117.0-255 : 25 hostnames found.\nDone with Fierce scan: http://ha.ckers.org/fierce/\nFound 62 entries.\nHave a nice day.\n" }, { "page_number": 121, "text": "Information Gathering\n[ 100 ]\nIt may take some time to finish the DNS enumeration using fierce.\nIn this section, we talked a lot about finding hostnames for a domain; \nyou may ask what are the purposes of these hostnames. In a penetration \ntesting project, one of the authors found a web meeting session after \ngetting the hostnames' result from the DNS analysis phase. That host \nallowed the author to join the ongoing web meeting session.\nDMitry\nDMitry (Deepmagic Information Gathering Tool) is an all-in-one information \ngathering tool. It can be used to gather the following information:\n•\t\nThe Whois record of a host by using the IP address or domain name\n•\t\nHost information from Netcraft.com\n•\t\nSubdomains in the target domain\n•\t\nThe e-mail address of the target domain\n•\t\nOpen, filtered, or closed port lists on the target machine by performing a \nport scan\nEven though this information can be obtained using several Kali Linux tools, it is \nvery handy to gather all of the information using a single tool and to save the report \nto one file.\nWe thought this tool is more suitable to be categorized under DNS \nanalysis instead of the Route analysis section because the capabilities \nare more about DNS analysis rather than in routing analysis.\nTo access DMitry from the Kali Linux menu, navigate to Applications | Kali Linux \n| Information Gathering | OSINT Analysis | dmitry or you can use the console \nand type the following command:\n# dmitry\nAs an example, let's do the following to a targethost:\n•\t\nPerform a Whois lookup\n•\t\nGet information from Netcraft.com\n•\t\nSearch for all the possible subdomains\n•\t\nSearch for all the possible e-mail addresses\n" }, { "page_number": 122, "text": "Chapter 4\n[ 101 ]\nThe command for performing the mentioned actions is as follows:\n# dmitry -iwnse targethost\nThe following is the abridged result of the preceding command:\nDeepmagic Information Gathering Tool\n\"There be some deep magic going on\"\nHostIP:192.168.xx.xx\nHostName:targethost\nGathered Netcraft information for targethost\n---------------------------------\nRetrieving Netcraft.com information for targethost\nNo uptime reports available for host: targethost\nGathered Subdomain information for targethost\n---------------------------------\nSearching Google.com:80...\nHostName:targethost\nHostIP:192.168.xx.xx\nHostName:www.ecom.targethost\nHostIP:192.168.xx.xx\nHostName:blogs.targethost\nHostIP:192.168.xx.xx\nHostName:static.targethost\nHostIP:192.168.xx.xx\nHostName:webmail.targethost\nHostIP:192.168.xx.xx\n...\nGathered E-Mail information for targethost\n---------------------------------\nFound 0 E-Mail(s) for host targethost, Searched 0 pages containing 0 \nresults\nWe can also use DMitry to perform a simple port scan by giving the following \ncommand:\n# dmitry -p targethost -f -b\nThe result of the preceding command is as follows:\nDeepmagic Information Gathering Tool\n\"There be some deep magic going on\"\nHostIP:192.168.xx.xx\n" }, { "page_number": 123, "text": "Information Gathering\n[ 102 ]\nHostName:targethost\nGathered TCP Port information for 192.168.xx.xx\n Port State\n...\n80/tcp open\n...\n135/tcp filtered\n136/tcp filtered\n137/tcp filtered\n138/tcp filtered\n139/tcp filtered\nPortscan Finished: Scanned 150 ports, 138 ports were in state closed\nFrom the preceding command, we find that the targethost is using a device to do \npacket filtering. It only allows incoming connections to port 80, which is commonly \nused for a web server.\nMaltego\nMaltego is an open source intelligence and forensics application. It allows you to \nmine and gather information and represent the information in a meaningful way. \nThe word open source in Maltego means that it gathers information from the open \nsource resources. After gathering the information, Maltego allows you to identify the \nkey relationship between the information gathered.\nMaltego is a tool that can graphically display the links between data, so it will make \nit easier to see the common aspects between pieces of information.\nMaltego allows you to enumerate the following Internet infrastructure information:\n•\t\nDomain names\n•\t\nDNS names\n•\t\nWhois information\n•\t\nNetwork blocks\n•\t\nIP addresses\n" }, { "page_number": 124, "text": "Chapter 4\n[ 103 ]\nIt can also be used to gather the following information about people:\n•\t\nCompanies and organizations related to the person\n•\t\nE-mail addresses related to the person\n•\t\nWebsites related to the person\n•\t\nSocial networks related to the person\n•\t\nPhone numbers related to the person\nKali Linux, by default, comes with Maltego 3.3.0 Kali Linux edition. The following \nare the limitations of the community version (http://www.paterva.com/web5/\nclient/community.php):\n•\t\nNot for commercial use\n•\t\nA maximum of 12 results per transform\n•\t\nYou need to register yourself on our website to use the client\n•\t\nAPI keys expire every couple of days\n•\t\nRuns on a (slower) server that is shared with all community users\n•\t\nCommunication between client and server is not encrypted\n•\t\nNot updated until the next major version\n•\t\nNo end user support\n•\t\nNo updates of transforms on server side\nThere are more than 70 transforms available in Maltego. The word transform refers \nto the information gathering phase of Maltego. One transform means that Maltego \nwill only do one phase of information gathering.\nTo access Maltego from the Kali Linux menu, navigate to Kali Linux | Information \nGathering | OSINT Analysis | maltego or you can use the console and type the \nfollowing command:\n# maltego\n" }, { "page_number": 125, "text": "Information Gathering\n[ 104 ]\nYou will see the Maltego welcome screen. After several seconds, you will see the \nfollowing Maltego start-up wizard that will help you set up the Maltego client for the \nfirst time:\nClick on Next to continue to the next window as shown in the following screenshot:\n" }, { "page_number": 126, "text": "Chapter 4\n[ 105 ]\nIn this window, you need to enter your login information to the Maltego community \nserver. If you don't have the login information, you need to register yourself first by \nclicking on the register here link.\nThe following screenshot shows the Register page:\nYou need to fill in your details into the corresponding fields provided, and click on \nthe Register! button to register.\nIf you already have the login details, you can enter them in the fields provided. \nWhen the login information is correct, the following information will be displayed:\n" }, { "page_number": 127, "text": "Information Gathering\n[ 106 ]\nYou will then need to select the transform seeds as shown in the \nfollowing screenshot:\nThe Maltego client will connect to the Maltego servers in order to get the transforms. \nIf Maltego has been initialized successfully, you will see the following screenshot:\n" }, { "page_number": 128, "text": "Chapter 4\n[ 107 ]\nThis means that your Maltego client initialization has been done successfully. Now \nyou can use the Maltego client.\nBefore we use the Maltego client, let's first see the Maltego interface:\nOn the top-left side of the preceding screenshot, you will see the Palette window. In \nthe Palette window, you can choose the entity type for which you want to gather the \ninformation. Maltego divides the entities into six groups as follows:\n•\t\nDevices such as phone or camera\n•\t\nInfrastructure such as AS, DNS name, domain, IPv4 address, MX record, NS \nrecord, netblock, URL, and website\n•\t\nLocations on Earth\n•\t\nPenetration testing such as built with technology\n•\t\nPersonal such as alias, document, e-mail address, image, person, phone \nnumber, and phrase\n•\t\nSocial Network such as Facebook object, Twitter entity, Facebook affiliation, \nand Twitter affiliation\nIn the top-middle of the preceding screenshot, you will see the different views: Main \nView, Bubble View, and Entity List. Views are used to extract information that is \nnot obvious from large graphs—where the analyst cannot see clear relationships \nby manual inspection of data. Main View is where you work most of the time. In \nBubble View, the nodes are displayed as bubbles, while in the Entity List tab, the \nnodes are simply listed in text format.\n" }, { "page_number": 129, "text": "Information Gathering\n[ 108 ]\nNext to the views, you will see different layout algorithms. Maltego supports the \nfollowing four layout algorithms:\n•\t\nBlock layout: This is the default layout and is used during mining\n•\t\nHierarchical layout: Think of this as a tree-based layout, such as a file \nmanager\n•\t\nCentrality layout: Nodes that are the most central to the graph (for example, \nmost incoming links) appear in the middle, with the other nodes scattered \naround it\n•\t\nOrganic layout: Nodes are packed together tightly in such a way that the \ndistance between each node and all the other nodes is minimized\nAfter a brief description of the Maltego client user interface, it's time for the action.\nLet's suppose you want to gather information about a domain. We will use \nthe domain example.com for this example. We will explore how to do this in the \nfollowing sections.\nCreate a new graph (Ctrl + T), go to the Palette tab, select Infrastructure, and click \non Domain. Drag it to the main window. If successful, you will see a domain called \npaterva.com in the main window. Double-click on the name and change it to your \ntarget domain, such as example.com, as shown in the following screenshot:\n" }, { "page_number": 130, "text": "Chapter 4\n[ 109 ]\nIf you right-click on the domain name, you will see all of the transforms that can be \ndone to the domain name:\n•\t\nDNS from domain\n•\t\nDomain owner's details\n•\t\nE-mail addresses from domain\n•\t\nFiles and documents from domain\n•\t\nOther transforms, such as To Person, To Phone numbers, and To Website\n•\t\nAll transforms\nLet's choose DomainToDNSNameSchema from domain transforms (Run \nTransform | Other Transforms | DomainToDNSNameSchema). The following \nscreenshot shows the result:\nAfter the DNS from Domain transform, we got information on the website address \n(www.example.com) related to the example.com domain.\nYou can run other transforms to the target domain.\nIf you want to change the domain, you need to save the current graph first. To save \nthe graph, click on the Maltego icon, and then select Save. The graph will be saved \nin the Maltego graph file format (.mtgx). To change the domain, just double-click on \nthe existing domain and change the domain name.\nNext, we will describe several tools that can be used for getting route information.\n" }, { "page_number": 131, "text": "Information Gathering\n[ 110 ]\nGetting network routing information\nThe tools in this category can be used to get the network routing information \nof a target. We will describe several tools that are commonly used for this \npurpose. Knowledge of the network routing information will allow the penetration \ntester to understand the network of the target machine, such as which path is taken \nby the packets sent from the penetration tester machine to the target machine. \nThe routing information will also give a clue as to whether the particular target is \nprotected by firewall.\nLet us see the several tools that can help you get routing information.\ntcptraceroute\nThe tcptraceroute tool can be used as a complement to the traceroute command. \nThe traceroute command sends a UDP or ICMP echo request packet with a Time \nTo Live (TTL) of one and increments the TTL until the packet reaches the target, \nwhile the tcptraceroute tool uses TCP SYN to send out the packet to the target.\nThe advantage of using tcptraceroute is that, nowadays, it is common to find a \nfirewall device filtered traceroute packet, so it will not be possible to trace the \nnetwork path to the target completely. However, this firewall still allows a packet \nto reach a particular TCP port in the target machine. By using tcptraceroute, we \nwill be able to find the network path to the target, even though there is a firewall in \nfront of it.\nThe tcptraceroute tool will receive a SYN/ACK packet if the port is open and a \nRST packet if the port is closed.\nTo access tcptraceroute, you can use the console and type the following command:\n# tcptraceroute\nThis will display usage information on your screen.\nLet's go for some action.\nWe run the traceroute command to trace our network route to the example.com \ndomain as follows:\n# traceroute www.example.com\nThe redacted result for this command is as follows:\ntraceroute to www.example.com (192.168.10.100), 30 hops max, 40 byte \npackets\n 1 192.168.1.1 (192.168.1.1) 8.382 ms 12.681 ms 24.169 ms\n" }, { "page_number": 132, "text": "Chapter 4\n[ 111 ]\n 2 1.static.192.168.xx.xx.isp (192.168.2.1) 47.276 ms 61.215 ms \n61.057 ms\n 3 * * *\n 4 74.subnet192.168.xx.xx.isp (192.168.4.1) 68.794 ms 76.895 ms \n94.154 ms\n 5 isp2 (192.168.5.1) 122.919 ms 124.968 ms 132.380 ms\n...\n15 * * *\n...\n30 * * *\nAfter route number 15, we are no longer able to get the route information. Usually, \nthis is because the traceroute packets are blocked by a filtering device.\nWe will try again using tcptraceroute, and we know that the targethost has an \nopen TCP port for the web server (80). We can use the following command:\n# tcptraceroute www.example.com\nThe result for this command is as follows:\nSelected device eth0, address 192.168.1.107, port 41884 for outgoing \npackets\nTracing the path to www.example.com (192.168.10.100) on TCP port 80 \n(www), 30 hops max\n 1 192.168.1.1 55.332 ms 6.087 ms 3.256 ms\n 2 1.static.192.168.xx.xx.isp (192.168.2.1) 66.497 ms 50.436 \nms 85.326 ms\n 3 * * *\n 4 74.subnet192.168.xx.xx.isp (192.168.4.1) 56.252 ms 28.041 ms \n34.607 ms\n 5 isp2 (192.168.5.1) 51.160 ms 54.382 ms 150.168 ms\n 6 192.168.6.1 106.216 ms 105.319 ms 130.462 ms\n 7 192.168.7.1 140.752 ms 254.555 ms 106.610 ms\n...\n14 192.168.14.1 453.829 ms 404.907 ms 420.745 ms\n15 192.168.15.1 615.886 ms 474.649 ms 432.609 ms\n16 192.168.16.1 [open] 521.673 ms 474.778 ms 820.607 ms\nThis time, our packet is able to reach the targethost, and it gives us all the route \ninformation from our machine to the targethost.\n" }, { "page_number": 133, "text": "Information Gathering\n[ 112 ]\ntctrace\nAnother tool that can be used to do route analysis is tctrace. It works by sending a \nTCP SYN packet to the target.\nTo access tctrace, you can use the console and type the following command:\n# tctrace -i -d\nIn the preceding command, –i is the network interface to the target and –d is the \ntarget.\nTo run tctrace to a target, the following command is used:\n# tctrace -i eth0 -d www.example.com\nThe following result is obtained:\n 1(1) [192.168.1.1]\n 2(1) [192.168.2.1]\n3(all) Timeout\n 4(3) [192.168.4.1]\n 5(1) [192.168.5.1]\n 6(1) [192.168.6.1]\n 7(1) [192.168.7.1]\n...\n14(1) [192.168.14.1]\n15(1) [192.168.15.1]\n16(1) [192.168.16.1] (reached; open)\nUtilizing the search engine\nThe Kali Linux tools grouped in this category can be used to collect domain, e-mail \naddress, and document metadata information from the target. These tools use a \nsearch engine to do their actions. The advantage of these tools is that they use search \nengine sites. So, you don't access the target website yourself, instead the search \nengine site will do that for you. As a result, the target website will not know about \nyour action.\nLet us explore several of these tools.\n" }, { "page_number": 134, "text": "Chapter 4\n[ 113 ]\ntheharvester\nThe theharvester tool is an e-mail accounts, username, and hostname/subdomains \ngathering tool. It collects information from various public sources. As of Version 2.2, \nthe public sources that are supported are as follows:\n•\t\nGoogle\n•\t\nGoogle profiles\n•\t\nBing\n•\t\nPGP\n•\t\nLinkedIn\n•\t\nYandex\n•\t\nPeople123\n•\t\nJigsaw\n•\t\nShodan\nTo access theharvester in Kali Linux, you can use the console and type the \nfollowing command:\n# theharvester\nThis will display the usage information and example on your screen.\nIf we want to find the e-mail addresses and hostnames for a target domain using \nGoogle and limit the result to 100, the following is the appropriate command:\n# theharvester -d example.com -l 100 -b google\nThe following e-mail addresses and hostnames are found:\n[-] Searching in Google:\n Searching 0 results...\n[+] Emails found:\n------------------\ninfo@example.com\nuser1@example.com\nuser2@example.com\nuser3@example.com\n[+] Hosts found in search engines:\n------------------------------------\n192.168.118.14:sd1.example.com\n192.168.118.14:sd2.example.com\n" }, { "page_number": 135, "text": "Information Gathering\n[ 114 ]\n192.168.118.14:event.example.com\n192.168.118.14:test.example.com\n203.34.118.7:nms.example.com\nFrom the preceding result, we notice that we are able to get several e-mail addresses \nand hostnames from the Google search engine.\nIf we want to gather more information, let's say we want to collect the username \nfrom the target, we can use linkedin.com to do this. The following is the command \nfor that:\n# theharvester -d example.com -l 100 -b linkedin\nThe following is the result:\n[-] Searching in Linkedin..\n Searching 100 results..\nUsers from Linkedin:\nuser1\nuser2\nuser3\nuser4\nuser5\nuser6\nTotal results: 6\nThe preceding list of usernames collected from LinkedIn will be useful in a penetration \ntesting step later if we want to do an attack, such as a social engineering attack.\nMetagoofil\nMetagoofil is a tool that utilizes the Google search engine to get metadata from \nthe documents available in the target domain. Currently, it supports the following \ndocument types:\n•\t\nWord document (.docx, .doc)\n•\t\nSpreadsheet document (.xlsx, .xls, .ods)\n•\t\nPresentation file (.pptx, .ppt, .odp)\n•\t\nPDF file (.pdf)\n" }, { "page_number": 136, "text": "Chapter 4\n[ 115 ]\nMetagoofil works by performing the following actions:\n•\t\nSearching for all of the preceding file types in the target domain using the \nGoogle search engine\n•\t\nDownloading all of the documents found and saving them to the local disk\n•\t\nExtracting the metadata from the downloaded documents\n•\t\nSaving the result in an HTML file\nThe metadata that can be found are as follows:\n•\t\nUsernames\n•\t\nSoftware versions\n•\t\nServer or machine names\nThis information can be used later on to help in the penetration testing phase.\nTo access Metagoofil, go to the console and execute the following command:\n# metagoofil\nThis will display a simple usage instruction and example on your screen.\nAs an example of Metagoofil usage, we will collect all the DOC and PDF documents \n(-t .doc,.pdf) from a target domain (-d example.com) and save them to a directory \nnamed test (-o test). We limit the search for each file type to 20 files (-l 20) and \nonly download five files (-n 5). The report generated will be saved to test.html (-f \ntest.html). We give the following command:\n# metagoofil -d example.com -l 20 -t doc,pdf –n 5 -f test.html -o test\nThe redacted result of this command is as follows:\n[-] Starting online search...\n[-] Searching for doc files, with a limit of 200\n Searching 100 results...\n Searching 200 results...\nResults: 191 files found\nStarting to download 5 of them:\n----------------------------------------\n[1/5] /support/websearch/bin/answer.py?answer=186645&%20\nform=bb&hl=en\nError downloading /support/websearch/bin/answer.\npy?answer=186645&%20form=bb&hl=en\n[2/5] http://www.example.com/documents/customerevidence/27402_\nCakewalk_final.doc\n" }, { "page_number": 137, "text": "Information Gathering\n[ 116 ]\n[3/5] http:// www.example.com/documents/customerevidence/5588_\nmarksspencer.doc\n[4/5] http:// www.example.com/documents/uk/Ladbrokes.doc\n[5/5] http:// www.example.com/~Gray/papers/PITAC_Interim_Report_8_98.\ndoc\n[-] Searching for pdf files, with a limit of 200\n Searching 100 results...\n Searching 200 results...\nResults: 202 files found\nStarting to download 5 of them:\n----------------------------------------\n[1/5] /support/websearch/bin/answer.py?answer=186645&%20\nform=bb&hl=en\nError downloading /support/websearch/bin/answer.\npy?answer=186645&%20form=bb&hl=en\n[2/5] http:// www.example.com/pubs/77954/sl021801.pdf\n[3/5] http:// www.example.com/pubs/152133/deepconvexnetwork-\ninterspeech2011-pub.pdf\n[x] Error in the parsing process\n[4/5] http:// www.example.com/en-us/collaboration/papers/uruguay.pdf\n[5/5] http:// www.example.com/pubs/63611/2002-droppo-icslpb.pdf\n[+] List of users found:\n--------------------------\nBenjamin Van Houten\nMarketing\nIT\nMay Yee\nsarah condon\nclarel\nJim Gray\n[+] List of software found:\n-----------------------------\nMicrosoft Office Word\nMicrosoft Word 10.0\nMicrosoft Word 9.0\nMicrosoft Word 8.0\nAcrobat Distiller 5.0.5 (Windows)\nAdobe PDF Library 8.0\nAdobe InDesign CS3 (5.0.2)\n" }, { "page_number": 138, "text": "Chapter 4\n[ 117 ]\n[+] List of paths and servers found:\n---------------------------------------\n'Macintosh HD:Temporary Items:AutoRecovery save of Congressio'\n'NCO Server:Staff (NCO Staff):Yolanda Comedy:IR22July:IR10Aug'\n'C:\\jim\\HPCC\\PACIT_Report_8_98.doc'\n[+] List of e-mails found:\n----------------------------\ngzweig@mail.example.com\nYou can see from the preceding result that we get a lot of information from the \ndocuments we have collected, such as the usernames and path information. We can \nuse the obtained usernames to look for patterns in the username and for launching a \nbrute force password attack on the usernames. But, be aware that doing a brute force \npassword attack on an account may have the risk of locking the user accounts. The \npath information can be used to guess the operating system that is used by the target. \nWe got all of this information without going to the domain website ourselves.\nMetagoofil is also able to generate information in a report format. The following \nscreenshot shows the generated report in HTML:\nIn the report generated, we get information about usernames, software version, \ne-mail address, and server information from the target domain.\n" }, { "page_number": 139, "text": "Information Gathering\n[ 118 ]\nSummary\nThis chapter introduced you to the information gathering phase. It is usually the first \nphase that is done during the penetration testing process. In this phase, you collect \nas much information as you can about the target organization. By knowing the target \norganization, it will be easier when we want to attack the target. There is a Chinese \nproverb which says:\nKnow yourself, know your enemy, and you shall win a hundred battles \nwithout loss.\nThis saying can't be more true than in penetration testing.\nWe described several tools included in Kali Linux that can be used for information \ngathering. We started by listing several public websites that can be used to gather \ninformation about the target organization. Next, we described how to use tools to \ncollect domain registration information. Then, we described tools that can be used to \nget DNS information. Later on, we explored tools for collecting routing information. In \nthe final part of the chapter, we described tools that utilize search engine capabilities.\nIn the next chapter, we will discuss how to discover a target.\n" }, { "page_number": 140, "text": "Target Discovery\nIn this chapter, we will describe the process of discovering machines on the \ntarget network using various tools available in Kali Linux. We will explain the \nfollowing topics:\n•\t\nA description of the target discovery process\n•\t\nThe method used to identify target machines using the tools in Kali Linux\n•\t\nThe steps required to find the operating systems of the target machines \n(operating system fingerprinting)\nTo help you understand these concepts easily, we will use a virtual network as the \ntarget network.\nStarting off with target discovery\nAfter we have gathered information about our target network from third-party \nsources, such as search engines, the next step would be to discover our target \nmachines. The purpose of this process is as follows:\n•\t\nTo find out which machine in the target network is available. If the target \nmachine is not available, we won't continue the penetration testing process \non that machine and move to the next machine.\n•\t\nTo find the underlying operating system used by the target machine.\nCollecting the previously mentioned information will help us during the \nvulnerabilities mapping process.\n" }, { "page_number": 141, "text": "Target Discovery\n[ 120 ]\nWe can utilize the tools provided in Kali Linux for the target discovery process. \nMost of these tools are available in the Information Gathering menu, with the \nfollowing submenus:\n•\t\nIdentify Live Hosts\n•\t\nOS Fingerprinting\nIn this chapter, we will only describe a few important tools in each category. \nThe tools are selected based on the functionality, popularity, and the tool \ndevelopment activity.\nIdentifying the target machine\nThe tools included in this category are used to identify the target machines that can \nbe accessed by a penetration tester. Before we start the identification process, we \nneed to know our client's terms and agreements. If the agreements require us to hide \npen-testing activities, we need to conceal our penetration testing activities. Stealth \ntechnique may also be applied for testing the Intrusion Detection System (IDS) or \nIntrusion Prevention System (IPS) functionality. If there are no such requirements, \nwe may not need to conceal our penetration testing activities.\nping\nThe ping tool is the most famous tool that is used to check whether a particular host \nis available. The ping tool works by sending an Internet Control Message Protocol \n(ICMP) echo request packet to the target host. If the target host is available and the \nfirewall is not blocking the ICMP echo request packet, it will reply with the ICMP \necho reply packet.\nThe ICMP echo request and ICMP echo reply are two of the available \nICMP control messages. For other ICMP control messages, you can refer \nto the following URL:\nhttps://en.wikipedia.org/wiki/Internet_Control_\nMessage_Protocol#Control_messages\nAlthough you can't find ping in the Kali Linux menu, you can open the console and \ntype the ping command with its options.\n" }, { "page_number": 142, "text": "Chapter 5\n[ 121 ]\nTo use ping, you can just type ping and the destination address as shown in the \nfollowing screenshot:\nIn Kali Linux, by default, ping will run continuously until you press Ctrl + C.\nThe ping tool has a lot of options, but the following are a few options that are \noften used:\n•\t\nThe -c count: This is the number of echo request packets to be sent.\n•\t\nThe -I interface address: This is the network interface of the source address. \nThe argument may be a numeric IP address (such as 192.168.56.102) or the \nname of the device (such as eth0). This option is required if you want to ping \nthe IPv6 link-local address.\n•\t\nThe -s packet size: This specifies the number of data bytes to be sent. The \ndefault is 56 bytes, which translates into 64 ICMP data bytes when combined \nwith the 8 bytes of the ICMP header data.\nLet's use the preceding information in practice.\nSuppose you are starting with internal penetration testing work. The customer gave \nyou access to their network using a LAN cable. And, they also gave you the list of \ntarget servers' IP addresses.\nThe first thing you would want to do before launching a full penetration testing \narsenal is to check whether these servers are accessible from your machine. You can \nuse ping for this task.\nThe target server is located at 192.168.56.102, while your machine has an IP \naddress of 192.168.56.101. To check the target server availability, you can give the \nfollowing command:\nping -c 1 192.168.56.102\n" }, { "page_number": 143, "text": "Target Discovery\n[ 122 ]\nBesides IP addresses, ping also accepts hostnames as \nthe destination.\nThe following screenshot is the result of the preceding ping command:\nFrom the preceding screenshot, we know that there is one ICMP echo request \npacket sent to the destination (IP address: 192.168.56.102). Also, the sending host (IP \naddress: 192.168.56.101) received one ICMP echo reply packet. The round-trip time \nrequired is 1.326 ms, and there is no packet loss during the process.\nLet's see the network packets that are transmitted and received by our machine. We \nare going to use Wireshark, a network protocol analyzer, on our machine to capture \nthese packets, as shown in the following screenshot:\nFrom the preceding screenshot, we can see that our host (192.168.56.101) sent \none ICMP echo request packet to the destination host (192.168.56.102). Since the \ndestination is alive and allows the ICMP echo request packet, it will send the ICMP \necho reply packet back to our machine.\nWe will cover Wireshark in more detail in the Network \nsniffers section in Chapter 10, Privilege Escalation.\nIf your target is using an IPv6 address, such as fe80::a00:27ff:fe43:1518, you \ncan use the ping6 tool to check its availability. You need to give the -I option for the \ncommand to work against the link-local address:\n# ping6 -c 1 fe80::a00:27ff:fe43:1518 -I eth0\nPING fe80::a00:27ff:fe43:1518(fe80::a00:27ff:fe43:1518) from \nfe80::a00:27ff:fe1c:5122 eth0: 56 data bytes\n64 bytes from fe80::a00:27ff:fe43:1518: icmp_seq=1 ttl=64 time=4.63 ms\n--- fe80::a00:27ff:fe43:1518 ping statistics ---\n" }, { "page_number": 144, "text": "Chapter 5\n[ 123 ]\n1 packets transmitted, 1 received, 0% packet loss, time 0ms\nrtt min/avg/max/mdev = 4.633/4.633/4.633/0.000 ms\nThe following screenshot shows the packets sent to complete the ping6 request:\nFrom the preceding screenshot, we know that ping6 is using the ICMPv6 \nrequest and reply.\nTo block the ping request, the firewall can be configured to only allow the ICMP \necho request packet from a specific host and drop the packets sent from other hosts.\narping\nThe arping tool is used to ping a host in the Local Area Network (LAN) using the \nAddress Resolution Protocol (ARP) request. You can use arping to ping a target \nmachine using its IP, host, or Media Access Control (MAC) address.\nThe arping tool operates on Open System Interconnection (OSI) layer 2 (network \nlayer), and it can only be used in a local network. Moreover, ARP cannot be routed \nacross routers or gateways.\nTo start arping, you can use the console to execute the following command:\n# arping\nThis will display brief usage information on arping.\nYou can use arping to get the target host's MAC address:\n# arping 192.168.56.102 -c 1\nARPING 192.168.56.102\n60 bytes from 08:00:27:43:15:18 (192.168.56.102): index=0 time=518.223 \nusec\n--- 192.168.56.102 statistics ---\n1 packets transmitted, 1 packets received, 0% unanswered (0 extra)\nFrom the previous command output, we can see that the target machine has a MAC \naddress of 08:00:27:43:15:18.\n" }, { "page_number": 145, "text": "Target Discovery\n[ 124 ]\nLet's observe the network packets captured by Wireshark on our machine during the \narping process:\nFrom the preceding screenshot, we can see that our network card (MAC address: \n08:00:27:1c:51:22) sends an ARP request to a broadcast MAC address \n(ff:ff:ff:ff:ff:ff), looking for the IP address 192.168.56.102. If the IP address \n192.168.56.102 exists, it will send an ARP reply mentioning its MAC address \n(08:00:27:43:15:18), as can be seen from packet number 2.\nHowever, if the IP address is not available, there will be no ARP replies, informing \nthe MAC address of the 192.168.56.103 IP address, as can be seen from the \nfollowing screenshot:\nAnother common use of arping is to detect duplicate IP addresses in a local \nnetwork. For example, your machine is usually connected to a local network using \nan IP address of 192.168.56.101; one day, you would like to change the IP address. \nBefore you can use the new IP address, you need to check whether that particular IP \naddress has already been used.\nYou can use the following arping command to help you detect whether the IP \naddress of 192.168.56.102 has been used:\n# arping -d -i eth0 192.168.56.102 -c 2 \n# echo $?\n1\nIf the code returns 1, it means that the IP address of 192.168.56.102 has been \nused by more than one machine. Whereas, if the code returns 0, it means that the IP \naddress is available.\nfping\nThe difference between ping and fping is that the fping tool can be used to send a \nping (ICMP echo) request to several hosts at once. You can specify several targets on \nthe command line, or you can use a file containing the hosts to be pinged.\n" }, { "page_number": 146, "text": "Chapter 5\n[ 125 ]\nIn the default mode, fping works by monitoring the reply from the target host. If \nthe target host sends a reply, it will be noted and removed from the target list. If the \nhost doesn't respond for a certain time limit, it will be marked as unreachable. By \ndefault, fping will try to send three ICMP echo request packets to each target.\nTo access fping, you can use the console to execute the following command:\n# fping -h\nThis will display the description of usage and options available in fping.\nThe following scenarios will give you an idea of the fping usage:\n•\t\nIf we want to know the alive hosts of 192.168.1.1, 192.168.1.100 and \n192.168.1.107 at once, we can use the following command:\nfping 192.168.1.1 192.168.1.100 192.168.1.107\nThe following is the result of the preceding command:\n192.168.1.1 is alive\n192.168.1.107 is alive\nICMP Host Unreachable from 192.168.1.112 for ICMP Echo sent to \n192.168.1.100\nICMP Host Unreachable from 192.168.1.112 for ICMP Echo sent to \n192.168.1.100\nICMP Host Unreachable from 192.168.1.112 for ICMP Echo sent to \n192.168.1.100\n192.168.1.100 is unreachable\n•\t\nWe can also generate the host list automatically without defining the IP \naddresses one by one and identifying the alive hosts. Let's suppose we want \nto know the alive hosts in the 192.168.56.0 network; we can use the -g \noption and define the network to check, using the following command:\n# fping -g 192.168.56.0/24\nThe result for the preceding command is as follows:\n192.168.56.101 is alive\n192.168.56.102 is alive\nICMP Host Unreachable from 192.168.56.102 for ICMP Echo sent to \n192.168.56.2\nICMP Host Unreachable from 192.168.56.102 for ICMP Echo sent to \n192.168.56.3\nICMP Host Unreachable from 192.168.56.102 for ICMP Echo sent to \n192.168.56.4\nICMP Host Unreachable from 192.168.56.102 for ICMP Echo sent to \n192.168.56.5\n" }, { "page_number": 147, "text": "Target Discovery\n[ 126 ]\nICMP Host Unreachable from 192.168.56.102 for ICMP Echo sent to \n192.168.56.6\n...\n192.168.56.252 is unreachable\n192.168.56.253 is unreachable\n192.168.56.254 is unreachable\n•\t\nIf we want to change the number of ping attempts made to the target, we can \nuse the -r option (retry limit) as shown in the following command line. By \ndefault, the number of ping attempts is three.\nfping -r 1 -g 192.168.1.1 192.168.1.10\nThe result of the command is as follows:\n192.168.1.1 is alive\n192.168.1.10 is alive\n192.168.1.2 is unreachable\n...\n192.168.1.9 is unreachable\n•\t\nDisplaying the cumulative statistics can be done by giving the -s option \n(print cumulative statistics) as follows:\nfping -s www.yahoo.com www.google.com www.msn.com\nThe following is the result of the preceding command line:\nwww.google.com is alive\nwww.yahoo.com is alive\nwww.msn.com is unreachable\n 3 targets\n 2 alive\n 1 unreachable\n 0 unknown addresses\n 4 timeouts (waiting for response)\n 6 ICMP Echos sent\n 2 ICMP Echo Replies received\n 0 other ICMP received\n 51.6 ms (min round trip time)\n 231 ms (avg round trip time)\n 411 ms (max round trip time)\n 4.150 sec (elapsed real time)\n" }, { "page_number": 148, "text": "Chapter 5\n[ 127 ]\nhping3\nThe hping3 tool is a command-line network packet generator and analyzer tool. \nThe capability to create custom network packets allows hping3 to be used for TCP/\nIP and security testing, such as port scanning, firewall rule testing, and network \nperformance testing.\nThe following are several other uses of hping3 according to the developer (http://\nwiki.hping.org/25):\n•\t\nTest firewall rules\n•\t\nTest Intrusion Detection System (IDS)\n•\t\nExploit known vulnerabilities in the TCP/IP stack\nTo access hping3, go to the console and type hping3.\nYou can give commands to hping3 in several ways, via the command line, \ninteractive shell, or script.\nWithout any given command-line options, hping3 will send a null TCP packet \nto port 0.\nIn order to change to a different protocol, you can use the following options in the \ncommand line to define the protocol:\nNo.\nShort option\nLong option\nDescription\n1\n-0\n--raw-ip\nThis sends raw IP packets\n2\n-1\n--icmp\nThis sends ICMP packets\n3\n-2\n--udp\nThis sends UDP packets\n4\n-8\n--scan\nThis indicates the scan mode\n5\n-9\n--listen\nThis indicates the listen mode\n" }, { "page_number": 149, "text": "Target Discovery\n[ 128 ]\nWhen using the TCP protocol, we can use the TCP packet without any flags (this is \nthe default behavior) or we can give one of the following flag options:\nNo.\nOption\nFlag name\n1\n-S\nsyn\n2\n-A\nack\n3\n-R\nrst\n4\n-F\nfin\n5\n-P\npsh\n6\n-U\nurg\n7\n-X\nxmas: flags fin, urg, psh set\n8\n-Y\nymas\nLet's use hping3 for several cases as follows:\n•\t\nSend one ICMP echo request packet to a 192.168.56.101 machine. \nThe options used are -1 (for the ICMP protocol) and -c 1 (to set the count \nto one packet):\nhping3 -1 192.168.56.101 -c 1\nThe following is the output of the command:\nFrom the preceding output, we can note that the target machine is alive \nbecause it has replied to our ICMP echo request.\nTo verify this, we captured the traffic using tcpdump and the following \nscreenshot shows the packets:\nWe can see that the target has responded with an ICMP echo reply packet.\n•\t\nBesides giving the options in the command line, you can also use hping3 \ninteractively. Open the console and type hping3. You will then see a prompt \nwhere you can type your Tcl commands.\n" }, { "page_number": 150, "text": "Chapter 5\n[ 129 ]\nThe following are several resources for Tcl:\nhttp://www.invece.org/tclwise/\nhttp://wiki.tcl.tk/\nFor the preceding example, the following is the corresponding Tcl script:\nhping send {ip(daddr=192.168.56.101)+icmp(type=8,code=0)}\nOpen a command-line window and give the following command to get a \nresponse from the target server:\nhping recv eth0\nAfter that, open another command-line window to input the sending request.\nThe following screenshot shows the response received:\n•\t\nYou can also use hping3 to check for a firewall rule. Let's suppose you have \nthe following firewall rules:\n°°\nAccept any TCP packets directed to port 22 (SSH)\n°°\nAccept any TCP packets related with an established connection\n°°\nDrop any other packets\nTo check these rules, you can give the following command in hping3 in order \nto send an ICMP echo request packet:\nhping3 -1 192.168.56.101 -c 1\nThe following code is the result:\nHPING 192.168.56.101 (eth0 192.168.56.101): icmp mode set, 28 \nheaders + 0 data bytes\n--- 192.168.56.101 hping statistic ---\n1 packets transmitted, 0 packets received, 100% packet loss\nround-trip min/avg/max = 0.0/0.0/0.0 ms\nWe can see that the target machine has not responded to our ping probe.\n" }, { "page_number": 151, "text": "Target Discovery\n[ 130 ]\nSend a TCP packet with the SYN flag set to port 22, and we will get a result \nas shown in the following screenshot:\nFrom the preceding screenshot, we can see that the target machine's firewall \nallows our syn packet to reach port 22.\nLet's check whether the UDP packet is allowed to reach port 22:\nFrom the preceding screenshot, we can see that the target machine's firewall does not \nallow our UDP packet to reach port 22. There are other things that you can do with \nhping3, but in this chapter, we'll only discuss a small subset of its capabilities. If you \nwant to learn more, you can consult the hping3 documentation site at http://wiki.\nhping.org.\nnping\nThe nping tool is a tool that allows users to generate network packets of a wide \nrange of protocols (TCP, UDP, ICMP, and ARP). You can also customize the fields in \nthe protocol headers, such as the source and destination port for TCP and UDP. The \ndifference between nping and other similar tools such as ping is that nping supports \nmultiple target hosts and port specification.\nBesides, it can be used to send an ICMP echo request just like in the ping command; \nnping can also be used for network stress testing, Address Resolution Protocol \n(ARP) poisoning, and the denial of service attacks.\nIn Kali Linux, nping is included with the Nmap package.\n" }, { "page_number": 152, "text": "Chapter 5\n[ 131 ]\nThe following are several probe modes supported by nping:\nNo.\nMode\nDescription\n1\n--tcp-\nconnect\nThis is an unprivileged TCP connect\n2\n--tcp\nThis is a TCP mode\n3\n--udp\nThis is a UDP mode\n4\n--icmp\nThis is an ICMP mode (default)\n5\n--arp\nThis is an ARP/RARP mode\n6\n--tr\nThis is a traceroute mode (it can only be used \nin the TCP/UDP/ICMP mode)\nAt the time of this writing, there is no Kali Linux menu yet for nping. So, you need to \nopen a console and type nping. This will display the usage and options' description.\nIn order to use nping to send an ICMP echo request to the target machines \n192.168.56.100, 192.168.56.101, and 192.168.56.102, you can give the \nfollowing command:\nnping -c 1 192.168.56.100-102\nThe following screenshot shows the command output:\nFrom the preceding screenshot, we know that only the 192.168.56.102 machine is \nsending back the ICMP echo reply packet.\n" }, { "page_number": 153, "text": "Target Discovery\n[ 132 ]\nIf the machine is not responding to the ICMP echo request packet as shown in the \nfollowing output, you can still find out whether it is alive by sending a TCP SYN \npacket to an open port in that machine:\nFor example, to send one (-c 1) TCP packet (--tcp) to the IP address \n192.168.56.102 port 22 (-p 22), you can give the following command:\nnping --tcp -c 1 -p 22 192.168.56.102\nOf course, you need to guess the ports which are open. We suggest that you try with \nthe common ports, such as 21, 22, 23, 25, 80, 443, 8080, and 8443.\nThe following screenshot shows the result of the mentioned example:\nFrom the preceding result, we can see that the remote machine (192.168.56.102) is \nalive because when we sent the TCP packet to port 22, the target machine responded.\nalive6\nIf you want to discover which machines are alive in an IPv6 environment, you can't \njust ask the tool to scan the whole network. This is because the address space is \nvery huge. You may find that the machines have a 64-bit network range. Trying to \ndiscover the machines sequentially in this network will require at least 264 packets. Of \ncourse, this is not a feasible task in the real world.\n" }, { "page_number": 154, "text": "Chapter 5\n[ 133 ]\nFortunately, there is a protocol called ICMPv6 Neighbor Discovery. This protocol \nallows an IPv6 host to discover the link-local and autoconfigured addresses of all \nother IPv6 systems on the local network. In short, you can use this protocol to find a \nlive host on the local network subnet.\nTo help you do this, there is a tool called alive6, which can send an ICMPv6 probe \nand is able to listen to the responses. This tool is part of the THC-IPv6 Attack Toolkit \ndeveloped by van Hauser from The Hackers Choice (http://freeworld.thc.org/\nthc-ipv6/) group.\nTo access alive6, go to the console and type alive6. This will display the \nusage information.\nSuppose you want to find the active IPv6 systems on your local IPv6 network, the \nfollowing command can be given with the assumption that the eth0 interface is \nconnected to the LAN:\nalive6 -p eth0\nThe following command lines are the result:\nAlive: fe80::a00:27ff:fe43:1518 [ICMP echo-reply]\nScanned 1 address and found 1 system alive\nTo mitigate against this, you can block the ICMPv6 echo request with the following \nip6tables command:\nip6tables –A INPUT –p ipv6-icmp –-type icmpv6-type 128 –j DROP\nThe following screenshot is the result after the target machine configures the \nip6tables rule:\ndetect-new-ip6\nThis tool can be used if you want to detect the new IPv6 address joining a local \nnetwork. This tool is part of the THC-IPv6 Attack Toolkit developed by van Hauser \nfrom The Hackers Choice group.\nTo access detect-new-ipv6, go to the console and type detect-new-ipv6. This will \ndisplay the usage information.\n" }, { "page_number": 155, "text": "Target Discovery\n[ 134 ]\nFollowing is a simple usage of this tool; we want to find the new IPv6 address that \njoined the local network:\ndetect-new-ip6 eth0\nThe following is the result of that command:\nStarted ICMP6 DAD detection (Press Control-C to end) ...\nDetected new ip6 address: fe80::a00:27ff:fe43:1518\npassive_discovery6\nThis tool can be used if you want to sniff out the local network to look for the IPv6 \naddress. This tool is part of the THC-IPv6 Attack Toolkit developed by van Hauser \nfrom The Hackers Choice group. Getting the IPv6 address without being detected by \nan IDS can be useful.\nTo access passive_discovery6, go to the console and type passive_discovery6. \nThis will display the usage information on the screen.\nThe following command is an example of running this tool:\npassive_discovery6 eth0\nThe following screenshot is the result of that command:\nThis tool simply waits for the ARP request/reply by monitoring the network, and \nthen it maps the answering hosts. The following are the IPv6 addresses that can be \ndiscovered by this tool on the network:\n•\t\nfe80::31ad:1227:d1d3:a002\n•\t\nfe80::a00:27ff:fe43:1518\nnbtscan\nIf you are doing an internal penetration testing on a Windows environment, the first \nthing you want to do is get the NetBIOS information. One of the tools that can be \nused to do this is nbtscan.\n" }, { "page_number": 156, "text": "Chapter 5\n[ 135 ]\nThe nbtscan tool will produce a report that contains the IP address, NetBIOS \ncomputer name, services available, logged in username, and MAC address of the \ncorresponding machines. The NetBIOS name is useful if you want to access the \nservice provided by the machine using the NetBIOS protocol that is connected to an \nopen share. Be careful as using this tool will generate a lot of traffic and it may be \nlogged by the target machines.\nTo find the meaning of each service in the NetBIOS report, you may \nwant to consult the Microsoft Knowledge Based on the NetBIOS \nSuffixes (16th Character of the NetBIOS Name) article at http://\nsupport.microsoft.com/kb/163409.\nTo access nbtscan, you can open the console and type nbtscan.\nAs an example, I want to find out the NetBIOS name of the computers located in my \nnetwork (192.168.1.0/24). The following is the command to be used:\nnbtscan 192.168.1.1-254\nThe following is the result of that command:\nDoing NBT name scan for addresses from 192.168.1.1-254\nIP address NetBIOS Name Server User MAC address\n-------------------------------------------------------------------------\n-----\n192.168.1.81 PC-001 \n00:25:9c:9f:b0:96\n192.168.1.90 PC-003 \n00:00:00:00:00:00\n...\nFrom the preceding result, we are able to find three NetBIOS names, PC-001, PC-003, \nand SRV-001.\nLet's find the service provided by these machines by giving the following command:\nnbtscan -hv 192.168.1.1-254\nOption -h will print the service in a human-readable name. While, option -v will \ngive more verbose output information.\nThe following is the result of this command:\nNetBIOS Name Table for Host 192.168.1.81:\nPC-001 Workstation Service\n" }, { "page_number": 157, "text": "Target Discovery\n[ 136 ]\nPC-001 File Server Service\nWORKGROUP Domain Name\nWORKGROUP Browser Service Elections\nAdapter address: 00:25:9c:9f:b0:96\nNetBIOS Name Table for Host 192.168.1.90:\nPC-003 Workstation Service\nPC-003\t Messenger Service\nPC-003 File Server Service\n__MSBROWSE__ Master Browser\nWORKGROUP Domain Name\nWORKGROUP Browser Service Elections\nWORKGROUP Domain Name\nWORKGROUP Master Browser\nAdapter address: 00:00:00:00:00:00\n...\nFrom the preceding result, we can see that there are two services available on PC-\n001: Workstation and File Server. While in PC-003, there are three services \navailable: Workstation, Messenger, and File Server. In our experience, this \ninformation is very useful because we know which machine has a file sharing \nservice. Next, we can continue to check whether the file sharing services are open so \nthat we can access the files stored on those file sharing services.\nOS fingerprinting\nAfter we know that the target machine is a live, we can then find out the operating \nsystem used by the target machine. This method is commonly known as Operating \nSystem (OS) fingerprinting. There are two methods of doing OS fingerprinting: \nactive and passive.\nIn the active method, the tool sends network packets to the target machine and then \ndetermines the operating system of the target machine based on the analysis done on \nthe response it has received. The advantage of this method is that the fingerprinting \nprocess is fast. However, the disadvantage is that the target machine may notice our \nattempt to get its operating system's information.\n" }, { "page_number": 158, "text": "Chapter 5\n[ 137 ]\nTo overcome the active method's disadvantage, there exists a passive method of OS \nfingerprinting. This method was pioneered by Michal Zalewsky when he released \na tool called p0f. The disadvantage of the passive method is that the process will be \nslower than the active method.\nIn this section, we will describe a couple of tools that can be used for OS \nfingerprinting.\np0f\nThe p0f tool is used to fingerprint an operating system passively. It can be used to \nidentify an operating system on the following machines:\n•\t\nMachines that connect to your box (SYN mode; this is the default mode)\n•\t\nMachines you connect to (SYN+ACK mode)\n•\t\nMachines you cannot connect to (RST+ mode)\n•\t\nMachines whose communications you can observe\nThe p0f tool works by analyzing the TCP packets sent during the network activities. \nThen, it gathers the statistics of special packets that are not standardized by default \nby any corporations. An example is that the Linux kernel uses a 64-byte ping \ndatagram, whereas the Windows operating system uses a 32-byte ping datagram; or \nthe Time To Live (TTL ) value. For Windows, the TTL value is 128, while for Linux \nthis TTL value varies between the Linux distributions. These information are then \nused by p0f to determine the remote machine's operating system.\nWhen using the p0f tool included with Kali Linux, we were not able to \nfingerprint the operating system on a remote machine. We figured out \nthat the p0f tool has not updated its fingerprint database. Unfortunately, \nwe couldn't find the latest version of the fingerprint database. So, we used \np0f v3 (Version 3.06b) instead. To use this version of p0f, just download \nthe TARBALL file from http://lcamtuf.coredump.cx/p0f3/\nreleases/p0f-3.06b.tgz and compile the code by running the build.\nsh script. By default, the fingerprint database file (p0f.fp) location is \nin the current directory. If you want to change the location, for example, \nif you want to change the location to /etc/p0f/p0f.fp, you need to \nchange this in the config.h file and recompile p0f. If you don't change \nthe location, you may need to use the -f option to define the fingerprint \ndatabase file location.\nTo access p0f, open a console and type p0f -h. This will display its usage and \noptions' description.\n" }, { "page_number": 159, "text": "Target Discovery\n[ 138 ]\nLet's use p0f to identify the operating system used in a remote machine we are \nconnecting to. Just type the following command in your console:\np0f –f /etc/p0f/p0f.fp -o p0f.log\nThis will read the fingerprint database from the /etc/p0f/p0f.fp file and save the \nlog information to the p0f.log file. It will then display the following information:\n--- p0f 3.06b by Michal Zalewski ---\n[+] Closed 1 file descriptor.\n[+] Loaded 314 signatures from '/etc/p0f/p0f.fp'.\n[+] Intercepting traffic on default interface 'eth0'.\n[+] Default packet filtering configured [+VLAN].\n[+] Log file 'p0f.log' opened for writing.\n[+] Entered main event loop.\nNext, you need to generate network activities involving a TCP connection, such \nas browsing to the remote machine or letting the remote machine to connect to \nyour machine.\nIf p0f has successfully fingerprinted the operating system, you will see information \nof the remote machine's operating system in the console and in the logfile (p0f.log).\nFollowing is the information displayed to the console:\n.-[ 192.168.56.101/42819 -> 192.168.56.102/80 (syn) ]-\n|\n| client = 192.168.56.101/42819\n| os = Linux 3.x\n| dist = 0\n| params = none\n| raw_sig = 4:64+0:0:1460:mss*10,7:mss,sok,ts,nop,ws:df,id+:0\n|\n`----\n.-[ 192.168.56.101/42819 -> 192.168.56.102/80 (mtu) ]-\n|\n| client = 192.168.56.101/42819\n| link = Ethernet or modem\n| raw_mtu = 1500\n" }, { "page_number": 160, "text": "Chapter 5\n[ 139 ]\n|\n`----\n.-[ 192.168.56.101/42819 -> 192.168.56.102/80 (syn+ack) ]-\n|\n| server = 192.168.56.102/80\n| os = Linux 2.6.x\n| dist = 0\n| params = none\n| raw_sig = 4:64+0:0:1460:mss*4,5:mss,sok,ts,nop,ws:df:0\n|\n`----\n.-[ 192.168.56.101/42819 -> 192.168.56.102/80 (mtu) ]-\n|\n| server = 192.168.56.102/80\n| link = Ethernet or modem\n| raw_mtu = 1500\n|\n`----\n.-[ 192.168.56.101/42819 -> 192.168.56.102/80 (http request) ]-\n|\n| client = 192.168.56.101/42819\n| app = Firefox 10.x or newer\n| lang = English\n| params = none\n| raw_sig = 1:Host,User-Agent,Accept=[text/html,application/\nxhtml+xml,application/xml;q=0.9,*/*;q=0.8],Accept-Language=[en-\nUS,en;q=0.5],Accept-Encoding=[gzip, deflate],Connection=[keep-\nalive]:Accept-Charset,Keep-Alive:Mozilla/5.0 (X11; Linux x86_64; rv:18.0) \nGecko/20100101 Firefox/18.0 Iceweasel/18.0.1\n|\n`----\n.-[ 192.168.56.101/42819 -> 192.168.56.102/80 (http response) ]-\n|\n" }, { "page_number": 161, "text": "Target Discovery\n[ 140 ]\n| server = 192.168.56.102/80\n| app = Apache 2.x\n| lang = none\n| params = none\n| raw_sig = 1:Date,Server,X-Powered-By=[PHP/5.2.4-2ubuntu5.10],?Content-\nLength,Keep-Alive=[timeout=15, max=100],Connection=[Keep-Alive],Content-\nType:Accept-Ranges:Apache/2.2.8 (Ubuntu) DAV/2\n|\n`----\nThe following screenshot shows the content of the logfile:\nBased on the preceding result, we know that the target is a Linux 2.6 machine. \nThe following screenshot shows the information from the target machine:\nBy comparing this information, we know that p0f got the OS information correctly. \nThe remote machine is using Linux Version 2.6.\nYou can stop p0f by pressing the Ctrl + C key combination.\nNmap\nNmap is a very popular and capable port scanner. Besides this, it can also be used to \nfingerprint a remote machine's operating system. It is an active fingerprinting tool. \nTo use this feature, you can give the -O option to the nmap command.\nFor example, if we want to fingerprint the operating system used on the \n192.168.56.102 machine, we use the following command:\nnmap –O 192.168.56.102\n" }, { "page_number": 162, "text": "Chapter 5\n[ 141 ]\nThe following screenshot shows the result of this command:\nNmap was able to get the correct operating system information after fingerprinting \nthe operating system of a remote machine.\nWe will talk more about Nmap in a later chapter.\nSummary\nIn this chapter, we discussed the target discovery process. We started by discussing \nthe purpose of target discovery: identifying the target machine and finding out the \noperating system used by the target machine. Then, we continued with the tools \nincluded with Kali Linux that can be used for identifying target machines.\nWe discussed the following tools: ping, arping, fping, hping3, nping, and \nnbtscan. We also discussed several tools specially developed to be used in an IPv6 \nenvironment, such as alive6, detect-new-ip6, and passive_discovery6.\nAt the end of this chapter, you learned about the tools that can be used to do OS \nfingerprinting: p0f, and briefly about the nmap capabilities for doing active operating \nsystem fingerprinting.\nIn the next chapter, we will talk about target enumeration and describe the tools \nincluded in Kali Linux that can be used for this purpose.\n" }, { "page_number": 163, "text": "" }, { "page_number": 164, "text": "Enumerating Target\nEnumerating target is a process that is used to find and collect information about \nports, operating systems, and services available on the target machines. This process \nis usually done after we have discovered that the target machines are available. In \npenetration testing practice, this task is conducted at the time of the discovery process.\nIn this chapter, we will discuss the following topics related to the target \nenumeration process:\n•\t\nA brief background concept describing port scanning and various port \nscanning types supported by the port scanning tools\n•\t\nThe tools that can be used to carry out network scanning task\n•\t\nThe tools that can be used to do SMB enumeration on the \nWindows environment\n•\t\nThe tools that can be used to do SNMP enumeration\n•\t\nThe tool that can be used to enumerate the IPsec VPN server\nThe goal of performing the enumeration process is to collect information about the \nservices available on the target systems. Later on, we will use this information to \nidentify vulnerabilities that exist on these services.\nIntroducing port scanning\nIn its simplest definition, port scanning can be defined as a method used to \ndetermine the state of the Transmission Control Protocol (TCP) and User Datagram \nProtocol (UDP) ports on the target machines. An open port may mean that there is a \nnetwork service listening on the port and the service is accessible, whereas a closed \nport means that there is no network service listening on that port.\n" }, { "page_number": 165, "text": "Enumerating Target\n[ 144 ]\nAfter getting the port's state, an attacker will then check the version of the software \nused by the network service and find out the vulnerability of that version of \nsoftware. For example, suppose that server A has web server software Version 1.0. A \nfew days ago, there was a security advisory released. The advisory gave information \nabout the vulnerability in web server software Version 1.0. If an attacker finds out \nabout server A's web server and is able to get the version information, the attacker \ncan use this information to attack the server. This is just a simple example of what an \nattacker can do after getting information about the services available on the machine.\nBefore we dig into the world of port scanning, let us discuss a little bit of the TCP/IP \nprotocol theory.\nUnderstanding the TCP/IP protocol\nIn the TCP/IP protocol suite, there are dozens of different protocols, but the most \nimportant ones are TCP and IP. IP provides addressing, datagram routing, and \nother functions for connecting one machine to another, while TCP is responsible for \nmanaging connections and provides reliable data transport between processes on \ntwo machines. The IP is located in the network layer (layer 3) in the Open Systems \nInterconnection (OSI) model, whereas TCP is located in the transport layer (layer 4) \nof OSI.\nBesides TCP, the other key protocol in the transport layer is UDP. You may ask what \nthe differences between these two protocols are.\nIn brief, TCP has the following characteristics:\n•\t\nThis is a connection-oriented protocol: Before TCP can be used for sending \ndata, the client and the server that want to communicate must establish a \nTCP connection using a three-way handshake mechanism as follows:\n1.\t The client initiates the connection by sending a packet containing a \nSYN (synchronize) flag to the server. The client also sends the initial \nsequence number (ISN) in the Sequence number field of the SYN \nsegment. This ISN is chosen randomly.\n2.\t The server replies with its own SYN segment containing its ISN. \nThe server acknowledges the client's SYN by sending an ACK \n(acknowledgment) flag containing the client's ISN + 1 value.\n3.\t The client acknowledges the server by sending an ACK flag \ncontaining the server ISN + 1. At this point, the client and the server \ncan exchange data.\n4.\t To terminate the connection, the TCP must follow the \ngiven mechanism:\n" }, { "page_number": 166, "text": "Chapter 6\n[ 145 ]\n1.\t The client sends a packet containing a FIN (finish) flag set.\n2.\t The server sends an ACK (acknowledgment) packet to inform \nthe client that the server has received the FIN packet.\n3.\t After the application server is ready to close, the server sends \na FIN packet.\n4.\t The client then sends the ACK packet to acknowledge \nreceiving the server's FIN packet. In a normal case, each side \n(client or server) can terminate its end of communication \nindependently by sending the FIN packet.\n•\t\nThis is a reliable protocol: TCP uses a sequence number and acknowledgment \nto identify packet data. The receiver sends an acknowledgment when it has \nreceived the packet. When a packet is lost, TCP will automatically retransmit it \nif it hasn't received any acknowledgment from the receiver. If the packets arrive \nout of order, TCP will reorder them before submitting it to the application.\nApplications that need to transfer files or important data use TCP, such as \nHypertext Transport Protocol (HTTP) and File Transfer Protocol (FTP).\nUDP has characteristics opposite to TCP, which are stated as follows:\n•\t\nThis is a connectionless protocol. To send data, the client and the server don't \nneed to establish a UDP connection first.\n•\t\nIt will do its best to send a packet to the destination, but if a packet is lost, \nUDP will not automatically resend it. It is up to the application to retransmit \nthe packet.\nApplications that can bear the loss of some packets, such as video streaming and \nother multimedia applications, use UDP. The other well-known applications that \nuse UDP are Domain Name System (DNS), Dynamic Host Configuration Protocol \n(DHCP), and Simple Network Management Protocol (SNMP).\nFor applications to be able to communicate correctly, the transport layer uses \naddressing called ports. A software process listens on a particular port number on \nthe server side, and the client machine sends data to that server port to be processed \nby the server application. The port numbers have a 16-bit address, and it can range \nfrom 0 to 65,535. To avoid a chaotic usage of port numbers, there are universal \nagreements on the port numbers' ranges as follows:\n•\t\nWell-known port numbers (0 to 1023): Port numbers in this range are reserved \nport numbers and are usually used by the server processes that are run by a \nsystem administrator or privileged user. The examples of the port numbers \nused by an application server are SSH (port 22), HTTP (port 80), HTTPS \n(port 443), and so on.\n" }, { "page_number": 167, "text": "Enumerating Target\n[ 146 ]\n•\t\nRegistered port numbers (1024 to 49151): Users can send a request to the \nInternet Assigned Number Authority (IANA) to reserve one of these port \nnumbers for their client-server application.\n•\t\nPrivate or dynamic port numbers (49152 to 65535): Anyone can use port \nnumbers in this range without registering themselves to IANA.\nAfter discussing the differences between TCP and UDP in brief, let us describe the \nTCP and UDP message format.\nUnderstanding the TCP and UDP message \nformat\nThe TCP message is called a segment. A TCP segment consists of a header and a \ndata section. The TCP header is often 20 bytes long (without TCP options). It can be \ndescribed using the following figure:\n0\nSource Port\n(16 bits)\n7\n15\n31\nDestination Port\n(16 bits)\nSequence Number\n(32 bits)\nAcknowledgment Number\n(32 bits)\nH. Len.\n(4 bits)\nRsvd.\n(4 bits)\nControl Bits\n(4 bits)\nChecksum\n(16 bits)\nWindow Size\n(16 bits)\nUrgent Pointer\n(16 bits)\nFollowing is a brief description of each field:\n•\t\nThe Source Port and the Destination Port have a length of 16 bits each. \nThe source port is the port on the sending machine that transmits the packet, \nwhile the destination port is the port on the target machine that receives \nthe packet.\n•\t\nThe Sequence Number (32 bits), in normal transmission, is the sequence \nnumber of the first byte of data of this segment.\n•\t\nThe Acknowledgment Number (32 bits) contains the sequence number from \nthe sender increased by one.\n" }, { "page_number": 168, "text": "Chapter 6\n[ 147 ]\n•\t\nH.Len. (4 bits) is the size of the TCP header in 32-bit words.\n•\t\nRsvd. is reserved for future use. It is a 4-bit field and must be zero.\n•\t\nThe Control Bits (control flags) contains eight 1-bit flags. In the original \nspecification (RFC 793; the RFC can be downloaded from http://www.ietf.\norg/rfc/rfc793.txt), the TCP only has six flags as follows:\n°°\nSYN: This flag synchronizes the sequence numbers. This bit is used \nduring session establishment.\n°°\nACK: This flag indicates that the Acknowledgment field in the TCP \nheader is significant. If a packet contains this flag, it means that it is \nan acknowledgement to the previously received packet.\n°°\nRST: This flag resets the connection.\n°°\nFIN: This flag indicates that the party has no more data to send. It is \nused to tear down a connection gracefully.\n°°\nPSH: This flag indicates that the buffered data should be pushed \nimmediately to the application rather than waiting for more data.\n°°\nURG: This flag indicates that the Urgent Pointer field in the TCP \nheader is significant. The urgent pointer refers to important data \nsequence numbers.\n•\t\nLater on, the RFC 3168 (the RFC can be downloaded from http://www.\nietf.org/rfc/rfc3168.txt) added two more extended flags as follows:\n°°\nCongestion Window Reduced (CWR): This is used by the data \nsender to inform the data receiver that the queue of outstanding \npackets to be sent has been reduced due to network congestion\n°°\nExplicit Connection Notification-Echo (ECN-Echo): This indicates \nthat the network connection is experiencing congestion\n•\t\nWindow Size (16 bits) specifies the number of bytes the receiver is willing \nto accept.\n•\t\nChecksum (16 bits) is used for error checking of the TCP header and data.\nThe flags can be set independent of each other.\nTo get more information on TCP, consult RFC 793 \nand RFC 3168.\n" }, { "page_number": 169, "text": "Enumerating Target\n[ 148 ]\nWhen performing a port scanning on the TCP port by using a SYN packet to the \ntarget machine, an attacker might face the following behaviors:\n•\t\nThe target machine responds with the SYN+ACK packet. If we receive this \npacket, we know that the port is open. This behavior is defined in the TCP \nspecification (RFC 793), which states that the SYN packet must be responded \nwith the SYN+ACK packet if the port is open without considering the SYN \npacket payload.\n•\t\nThe target machine sends back a packet with the RST and ACK bit set. This \nmeans that the port is closed.\n•\t\nThe target machine sends an ICMP message such as ICMP Port \nUnreachable, which means that the port is not accessible to us most likely \nbecause it is blocked by the firewall.\n•\t\nThe target machine sends nothing back to us. It may indicate that there is no \nnetwork service listening on that port or that the firewall is blocking our SYN \npacket silently.\nFrom a pentester's point of view, interesting behavior is when the port is open because \nthis means that there is a service available on that port that can be tested further.\nIf you conduct a port scanning attack, you should understand the various TCP \nbehaviors listed in order to be able to attack more effectively.\nWhen scanning for UDP ports, you will see different behaviors, as will be \nexplained later on.\nBefore we go to see various UDP behaviors, let's see the UDP header format first as \nshown in the following figure:\n0\nSource Port\n(16 bits)\n15\n31\nDestination Port\n(16 bits)\nUDP Length\n(16 bits)\nUDP Checksum\n(16 bits)\nThe following is a brief explanation of each field in the UDP header depicted in the \npreceding figure:\n•\t\nJust like the TCP header, the UDP header also has the Source Port and the \nDestination Port, each of which has 16-bits length. The source port is the port \non the sending machine that transmits the packet, while the destination port \nis the port on the target machine that receives the packet.\n•\t\nUDP Length is the length of the UDP header.\n•\t\nUDP Checksum (16 bits) is used for error checking of the UDP header \nand data.\n" }, { "page_number": 170, "text": "Chapter 6\n[ 149 ]\nNote that there are no Sequence Number, Acknowledgement Number, and Control \nBits fields in the UDP header.\nDuring a port scanning activity to the UDP port on the target machine, an attacker \nmight face the following behaviors:\n•\t\nThe target machine responds with a UDP packet. If we receive this packet, \nwe know that the port is open.\n•\t\nThe target machine sends an ICMP message such as ICMP Port \nUnreachable. It can be concluded that the port is closed. However, if the \nmessage sent is not an ICMP unreachable message, it means that the port is \nfiltered by the firewall.\n•\t\nThe target machine sends nothing back to us. This may indicate one of the \nfollowing situations:\n°°\nThe port is closed\n°°\nThe inbound UDP packet is blocked\n°°\nThe response is blocked\nUDP port scanning is less reliable when compared to TCP port scanning because \nsometimes, the UDP port is open but the service listening on that port is looking for a \nspecific UDP payload. Thus, the the service will not send any replies.\nNow that we have briefly described the port scanning theory, let's put this into \npractice. In the following sections, we will look at several tools that can be used to \nhelp us perform network scanning.\nFor the practical scenarios in this chapter, we will utilize a Metasploitable virtual \nmachine, as explained in Chapter 1, Beginning with Kali Linux, as our target machine. \nIt has an IP address of 192.168.56.103, while our attacking machine has an IP \naddress of 192.168.56.102.\nThe network scanner\nIn this section, we will look at several tools that can be used to find open ports, \nfingerprint the remote operating system, and enumerate the services on the \nremote machine.\nService enumeration is a method that is used to find the service version that is \navailable on a particular port on the target system. This version information is \nimportant because with this information, the penetration tester can search for \nsecurity vulnerabilities that exist for that software version.\n" }, { "page_number": 171, "text": "Enumerating Target\n[ 150 ]\nSome system administrators often change the port number, a service is listening \non. For example, an SSH service may be bound to port 22 (as a convention), but a \nsystem administrator may change it to be bound to port 2222. If the penetration \ntester only does a port scan to the common port of SSH, it may not find that service. \nThe penetration tester will also have difficulties when dealing with proprietary \napplications running on non-standard ports. By using the service enumeration tools, \nthese two problems can be mitigated, so there is a chance that the service can be \nfound, regardless of the port it binds to.\nNmap\nNmap is a very comprehensive, feature- and fingerprint-rich, and widely used port \nscanner by all of the IT security community. It is written and maintained by Fyodor. \nIt is a must-have tool for a penetration tester because of its quality and flexibility.\nBesides being used as a port scanner, Nmap has several other capabilities as follows:\n•\t\nHost discovery: Nmap can be used to find live hosts on the target systems. \nBy default, Nmap will send an ICMP echo request, a TCP SYN packet to port \n443, a TCP ACK packet to port 80, and an ICMP timestamp request to carry \nout the host discovery.\n•\t\nService/version detection: After Nmap has discovered the ports, it can \nfurther check for the service protocol, the application name, and the version \nnumber used on the target machine.\n•\t\nOperating system detection: Nmap sends a series of packets to the remote \nhost and examines the responses. Then, it compares these responses with its \noperating system fingerprint database and prints out the details if there is a \nmatch. If it is not able to determine the operating system, Nmap will provide \na URL where you can submit the fingerprint to update its operating system \nfingerprint database. Of course, you should submit the fingerprint if you \nknow the operating system used on the target system.\n•\t\nNetwork traceroute: It is performed to determine the port and protocol \nthat is most likely to reach the target system. Nmap traceroute starts with \na high value of Time to Live (TTL) and decrements it until the TTL value \nreaches zero. \n•\t\nNmap Scripting Engine: With this feature, Nmap can be extended. If you \nwant to add a check that is not included with the default Nmap, you can do \nso by writing the check using the Nmap scripting engine. Currently, there are \nchecks for vulnerabilities in network services and for enumerating resources \non the target system.\n" }, { "page_number": 172, "text": "Chapter 6\n[ 151 ]\nIt is good practice to always check for new versions of Nmap. If you find the latest \nversion of Nmap available for Kali Linux, you can update your Nmap by issuing the \nfollowing commands:\napt-get update\napt-get install nmap\nTo start Nmap, go to the console to execute the following command:\nnmap\nThis will display all of the Nmap options with their descriptions.\nA new user to Nmap will find the available options quite overwhelming.\nFortunately, you only need one option to scan for the remote machine. That option is \nyour target IP address or hostname if you have set up the DNS correctly. This is done \nwith the following command:\nnmap 192.168.56.103\nThe following is the result of the scan without any other options:\nNmap scan report for 192.168.56.103\nHost is up (0.0046s latency).\nNot shown: 977 closed ports\nPORT STATE SERVICE\n21/tcp open ftp\n22/tcp open ssh\n23/tcp open telnet\n25/tcp open smtp\n53/tcp open domain\n80/tcp open http\n111/tcp open rpcbind\n139/tcp open netbios-ssn\n445/tcp open microsoft-ds\n512/tcp open exec\n513/tcp open login\n514/tcp open shell\n1099/tcp open rmiregistry\n1524/tcp open ingreslock\n2049/tcp open nfs\n" }, { "page_number": 173, "text": "Enumerating Target\n[ 152 ]\n2121/tcp open ccproxy-ftp\n3306/tcp open mysql\n5432/tcp open postgresql\n5900/tcp open vnc\n6000/tcp open X11\n6667/tcp open irc\n8009/tcp open ajp13\n8180/tcp open unknown\nMAC Address: 08:00:27:43:15:18 (Cadmus Computer Systems)\nNmap done: 1 IP address (1 host up) scanned in 13.49 seconds\nFrom the preceding result, we can see that the target machine is very vulnerable to \nattack because it has many open ports.\nBefore we continue to use Nmap, let's take a look at the port states that can be \nidentified by Nmap. There are six port states that are recognized by Nmap as follows:\n•\t\nOpen: This means that there is an application accepting a TCP connection, \nUDP datagram, or SCTP association.\n•\t\nClosed: This means that although the port is accessible, there is no \napplication listening on the port.\n•\t\nFiltered: This means that Nmap can't determine whether the port is open \nor not because there is a packet-filtering device blocking the probe to reach \nthe target.\n•\t\nUnfiltered: This means that the port is accessible, but Nmap cannot \ndetermine whether it is open or closed.\n•\t\nOpen|Filtered: This means that Nmap is unable to determine whether a port \nis open or filtered. This happens when a scan to open ports doesn't give a \nresponse. It can be achieved by setting the firewall to drop packets.\n•\t\nClosed|Filtered: This means Nmap is unable to determine whether a port is \nclosed or filtered.\nAfter describing the port states, we will describe several options that are \ncommonly used during penetration testing, and after that, we will use those \noptions in our practice.\n" }, { "page_number": 174, "text": "Chapter 6\n[ 153 ]\nNmap target specification\nNmap will treat everything on the command line that isn't an option or option \nargument as target host specification. We suggest that you use the IP address \nspecification instead of the hostname. By using the IP address, Nmap doesn't need to \ndo DNS resolution first. This will speed up the port scanning process.\nIn the current version, Nmap supports the following IPv4 address specifications:\n•\t\nA single host such as 192.168.0.1.\n•\t\nA whole network of adjacent hosts by using the CIDR notation such as \n192.168.0.0/24. This specification will include 256 IP addresses ranging \nfrom 192.168.0.0 to 192.168.0.255.\n•\t\nAn octet range addressing such as 192.168.2-4,6.1. This addressing will \ninclude four IP addresses: 192.168.2.1, 192.168.3.1, 192.168.4.1, and \n192.168.6.1.\n•\t\nMultiple host specifications such as 192.168.2.1 172.168.3-5,9.1\nFor the IPv6 address, Nmap only supports the fully qualified IPv6 format and \nhostname such as fe80::a8bb:ccff:fedd:eeff%eth0.\nBesides getting the target specification from the command line, Nmap also accepts \ntarget definition from a text file by using the -iL option. This \noption is useful if we already have the IP addresses from another program.\nMake sure that the entries in that file use the Nmap-supported target specification \nformat. Each entry must be separated by spaces, tabs, or a new line.\nThe following code is a sample of that file:\n 192.168.1.1-254\n 192.168.2.1-254\nNow let's scan a network of 192.168.56.0/24. We want to see the packets \nsent by Nmap. To monitor the packets sent, we can use a packet capture utility \nsuch as tcpdump.\nOpen a console and type the following command:\ntcpdump -nnX tcp and host 192.168.56.102 \nThe 192.168.56.102 IP address belongs to our machine, which launches Nmap. \nYou need to adjust it to your configuration.\n" }, { "page_number": 175, "text": "Enumerating Target\n[ 154 ]\nOpen another console on the same machine and type the following command:\nnmap 192.168.56.0/24\nIn the tcpdump console, you will see the following packet:\n22:42:12.107532 IP 192.168.56.102.49270 > 192.168.56.103.23: \n Flags [S], seq 239440322, win 1024, options [mss 1460], length 0\n 0x0000: 4500 002c eb7f 0000 3006 ad2e c0a8 3866 E..,....0.....8f\n 0x0010: c0a8 3867 c076 0017 0e45 91c2 0000 0000 ..8g.v...E......\n 0x0020: 6002 0400 4173 0000 0204 05b4 `...As......\nFrom the preceding packet information, we know that the attacking machine sent a \npacket with a SYN flag set from port 49270 to the target machine port 23 (Telnet). \nThe SYN flag is set by default if Nmap is run by the privileged user, such as root in \nKali Linux.\nThe following screenshot shows other packets sent by the attacking machine to other \nmachines and ports on the target network:\nIf the remote machine responds, the response packet will look like the following code:\n22:36:19.939881 IP 192.168.56.103.1720 > 192.168.56.102.47823: \n Flags [R.], seq 0, ack 1053563675, win 0, length 0\n 0x0000: 4500 0028 0000 4000 4006 48b2 c0a8 3867 E..(..@.@.H...8g\n 0x0010: c0a8 3866 06b8 bacf 0000 0000 3ecc 1b1b ..8f........>...\n 0x0020: 5014 0000 a243 0000 0000 0000 0000 P....C........\n" }, { "page_number": 176, "text": "Chapter 6\n[ 155 ]\nNote the flag sent—it is denoted by the character R which is reset. It means that \nport 1720 in the target machine is closed. We can verify this with the previous \nNmap result.\nHowever, if the port is open, you will see the following network traffic:\n22:42:12.108741 IP 192.168.56.103.23 > 192.168.56.102.49270: \n Flags [S.], seq 1611132106, ack 239440323, win 5840, \n options [mss 1460], length 0\n 0x0000: 4500 002c 0000 4000 4006 48ae c0a8 3867 E..,..@.@.H...8g\n 0x0010: c0a8 3866 0017 c076 6007 ecca 0e45 91c3 ..8f...v`....E..\n 0x0020: 6012 16d0 e1bf 0000 0204 05b4 0000\nYou can see that the packet in the preceding code is to acknowledge the sequence \nnumber from the previous packet displayed. This packet has an acknowledgement \nnumber of 239440323, while the previous packet had a sequence number of \n239440322.\nNmap TCP scan options\nTo be able to use most of the TCP scan options, Nmap needs a privileged user \n(a root-level account in the Unix world or an administrator-level account in the \nWindows world). This is used to send and receive raw packets. By default, Nmap \nwill use a TCP SYN scan, but if Nmap doesn't have a privileged user, it will use the \nTCP connect scan. The various scans used by Nmap are as follows:\n•\t\nTCP connect scan (-sT): This option will complete the three-way handshake \nwith each target port. If the connection succeeds, the port is considered open. \nAs a result of the need to do a three-way handshake for each port, this scan \ntype is slow and it will most likely be logged by the target. This is the default \nscan option used if Nmap is run by a user who doesn't have any privileges.\n•\t\nSYN scan (-sS): This option is also known as half-open or SYN stealth. \nWith this option, Nmap sends a SYN packet and then waits for a response. \nA SYN/ACK response means that the port is listening, while the RST/\nACK response means that the port is not listening. If there is no response or \nan ICMP unreachable error message response, the port is considered to be \nfiltered. This scan type can be performed quickly and because the three-way \nhandshake is never completed, it is unobtrusive and stealthy. This is the \ndefault scan option if you run Nmap as a privileged user.\n•\t\nTCP NULL scan (-sN), FIN scan (-sF), and XMAS scan (-sX): The NULL \nscan doesn't set any control bits. The FIN scan only sets the FIN flag bit, \nand the XMAS scan sets the FIN, PSH, and URG flags. If an RST packet is \nreceived as a response, the port is considered closed, while no response \nmeans that the port is open/filtered.\n" }, { "page_number": 177, "text": "Enumerating Target\n[ 156 ]\n•\t\nTCP Maimon scan (-sM): The TCP Maimon scan was discovered by Uriel \nMaimon. A scan of this type will send a packet with the FIN/ACK flag bit \nset. BSD-derived systems will drop the packet if the port is open, and it will \nrespond with RST if the port is closed.\n•\t\nTCP ACK scan (-sA): This scan type is used to determine whether a firewall \nis stateful or not and which ports are filtered. A network packet of this type \nonly sets the ACK bit. If RST is returned, it means that the target is unfiltered.\n•\t\nTCP Window scan (-sW): This scan type works by examining the TCP \nWindow field of the RST packet's response. An open port will have a positive \nTCP Window value, while a closed port will have a zero window value.\n•\t\nTCP Idle scan (-sI): Using this technique, no packets are sent to the target \nby your machine, instead the scan will bounce off to a zombie host you \nspecify. An IDS will report the zombie as the attacker.\nNmap also supports you in creating your own custom TCP scan by giving you \nthe option of scanflags. The argument to that option can be numerical, such as 9 \nfor PSH and FIN, or symbolic names. Just put together any combination of URG, \nACK, PSH, RST, SYN, FIN, ECE, CWR, ALL, and NONE in any order; for example, \n--scanflags URGACKPSH will set the flags URG, ACK, and PSH.\nNmap UDP scan options\nWhile the TCP scan has many types of scans, the UDP scan only has one type and \nthat is the UDP scan (-sU). Even though the UDP scan is less reliable compared to \nthe TCP scan, as a penetration tester you should not ignore this scan because there \nmay be interesting services located on these UDP ports.\nThe biggest problem with the UDP scan is how to perform the scan quickly. A Linux \nkernel limits the sending of the ICMP Port Unreachable message to one message \nper second. Doing a UDP scanning of 65,536 ports to a machine will take more than \n18 hours to complete.\nTo help mitigate this problem, there are several ways that can be used as follows:\n•\t\nRunning the UDP scan in parallel\n•\t\nScanning the most popular ports first\n•\t\nScanning behind the firewall\n•\t\nSetting the --host-timeout option to skip slow hosts\nThese methods can help to decrease the time required for doing UDP port scans.\n" }, { "page_number": 178, "text": "Chapter 6\n[ 157 ]\nLet's see a scenario where we want to find which UDP ports are open on the target \nmachine. To speed up the scanning process, we will only check for ports 53 (DNS) \nand 161 (SNMP). The following is the command used to do this:\nnmap -sU 192.168.56.103 -p 53,161\nThe following is the result of this command:\nNmap scan report for 192.168.56.103\nHost is up (0.0016s latency).\nPORT STATE SERVICE\n53/udp open domain\n161/udp closed snmp\nNmap port specification\nIn the default configuration, Nmap will only scan the 1000 most common ports for \neach protocol randomly. The nmap-services file contains a popularity score for the \nselection of top ports.\nTo change that configuration, Nmap provides several options as follows:\n•\t\n-p port_range: Scan only the defined ports. To scan port 1 to 1024, the \ncommand is -p 1-1024. To scan port 1 to 65535, the command is -p-\n•\t\n-F (fast): This will scan only 100 common ports\n•\t\n-r (don't randomize port): This option will set sequential port scanning \n(from lowest to highest)\n•\t\n--top-ports <1 or greater>: This option will only scan the N highest-\nratio ports found in the nmap-service file\nTo scan for ports 22 and 25 using the TCP NULL scan method, you can use the \nfollowing command:\nnmap -sN -p 22,25 192.168.56.103\n" }, { "page_number": 179, "text": "Enumerating Target\n[ 158 ]\nThe following command lines are the result:\nNmap scan report for 192.168.56.103\nHost is up (0.00096s latency).\nPORT STATE SERVICE\n22/tcp open|filtered ssh\n25/tcp open|filtered smtp\n80/tcp open|filtered http\n3306/tcp open|filtered mysql\nMAC Address: 08:00:27:43:15:18 (Cadmus Computer Systems)\nNmap done: 1 IP address (1 host up) scanned in 14.38 seconds\nThe following are the packet's dumped snippets:\n23:23:38.581818 IP 192.168.56.102.61870 > 192.168.56.103.22: Flags [], \nwin 1024, length 0\n 0x0000: 4500 0028 06e4 0000 2f06 92ce c0a8 3866 E..(..../.....8f\n 0x0010: c0a8 3867 f1ae 0016 dd9e bf90 0000 0000 ..8g............\n 0x0020: 5000 0400 2ad2 0000 P...*...\n23:23:38.581866 IP 192.168.56.102.61870 > 192.168.56.103.25: Flags [], \nwin 1024, length 0\n 0x0000: 4500 0028 1117 0000 3106 869b c0a8 3866 E..(....1.....8f\n 0x0010: c0a8 3867 f1ae 0019 dd9e bf90 0000 0000 ..8g............\n 0x0020: 5000 0400 2acf 0000 P...*...\n23:23:39.683483 IP 192.168.56.102.61871 > 192.168.56.103.25: Flags [], \nwin 1024, length 0\n 0x0000: 4500 0028 afaf 0000 2706 f202 c0a8 3866 E..(....'.....8f\n 0x0010: c0a8 3867 f1af 0019 dd9f bf91 0000 0000 ..8g............\n 0x0020: 5000 0400 2acc 0000 P...*...\n23:23:39.683731 IP 192.168.56.102.61871 > 192.168.56.103.22: Flags [], \nwin 1024, length 0\n 0x0000: 4500 0028 5488 0000 3506 3f2a c0a8 3866 E..(T...5.?*..8f\n 0x0010: c0a8 3867 f1af 0016 dd9f bf91 0000 0000 ..8g............\n 0x0020: 5000 0400 2acf 0000 P...*... \n" }, { "page_number": 180, "text": "Chapter 6\n[ 159 ]\nFrom the packets displayed in the preceding code, we can see that:\n•\t\nIn the first and second packet, the attacking machine checks whether port 22 \non the target machine is open. After a period of time, it checks port 25 on the \ntarget machine.\n•\t\nIn the third and fourth packet, the attacking machine checks whether port 25 \non the target machine is open. After a period of time, it checks port 22 on the \ntarget machine.\n•\t\nAfter waiting for some time, as there is still no response from the target \nmachine, Nmap concludes that those two ports are open or filtered.\nNmap output options\nThe Nmap result can be saved to an external file. This option is useful if you want to \nprocess the Nmap result with other tools.\nEven if you save the output to a file, Nmap still displays the result on the screen.\nNmap supports several output formats as follows:\n•\t\nInteractive output: This is a default output format, and the result is sent to \nthe standard output.\n•\t\nNormal output (-oN): This format is similar to the interactive output, but it \ndoesn't include the runtime information and warnings.\n•\t\nXML output (-oX): This format can be converted to an HTML format, parsed \nby the Nmap graphical user interface, or imported to the database. We \nsuggest you use this output format as much as you can.\n•\t\nGrepable output (-oG): This format is deprecated, but it is still quite popular. \nGrepable output consists of comments (lines starting with a pound (#)) \nand target lines. A target line includes a combination of six labeled fields \nseparated by tabs and followed by a colon. The fields are Host, Ports, \nProtocols, Ignored State, OS, Seq Index, IP ID Seq, and Status. We \nsometimes use this output if we want to process the Nmap output using the \nUNIX commands such as grep and awk.\nYou can use the –oA option to save the Nmap result in three \nformats at once (normal, XML, and grepable).\nTo save a scan result to an XML file (myscan.xml), use the following command:\nnmap 192.168.56.103 -oX myscan.xml\n" }, { "page_number": 181, "text": "Enumerating Target\n[ 160 ]\nThe following is a snippet of the XML file:\n\n\n\n\n\n50003,50006,50300,50389,50500,50636,50800,51103,51493, \n52673,52822,52848,52869,54045,54328,55055-55056,55555,55600,56737-\n56738,57294,57797,58080,60020,60443,61532,61900,62078,63331,64623, \n64680,65000,65129,65389\"/>\n\n\n\n
\n
\nIt is easier to read the HTML file instead of the XML file, so we'll convert the \nXML format to HTML. You can use the xsltproc program to do the conversion. \nThe following command is used to convert the XML file to an HTML file:\nxsltproc myscan.xml -o myscan.html\n" }, { "page_number": 182, "text": "Chapter 6\n[ 161 ]\nThe following is the HTML report as displayed by the Iceweasel web browser \nincluded in Kali Linux:\nIf you want to process the Nmap XML output to your liking, there are several \nprogramming language generic XML libraries that you can use for this purpose. \nAlso, there are several libraries specifically developed to work with an Nmap output:\n•\t\nPerl: Nmap-Parser (http://search.cpan.org/dist/Nmap-Parser/)\n•\t\nPython: python-nmap (http://xael.org/norman/python/python-nmap/)\n•\t\nRuby: Ruby Nmap (http://rubynmap.sourceforge.net/)\n•\t\nPowerShell: PowerShell script to parse nmap XML output (http://www.\nsans.org/windows-security/2009/06/11/powershell-script-to-\nparse-nmap-xml-output)\nNmap timing options\nNmap comes with six timing modes that you can set with options (-T):\n•\t\nparanoid (0): In this timing mode, a packet is sent every 5 minutes. The \npackets are sent in serial. This mode is useful to avoid IDS detection.\n•\t\nsneaky (1): This mode sends a packet every 15 seconds, and there are no \npackets sent in parallel.\n" }, { "page_number": 183, "text": "Enumerating Target\n[ 162 ]\n•\t\npolite (2): This mode sends a packet every 0.4 seconds and there is no \nparallel transmission.\n•\t\nnormal (3): This mode sends multiple packets to multiple targets \nsimultaneously. This is the default timing mode used by Nmap. It balances \nbetween time and network load.\n•\t\naggressive (4): Nmap will scan a given host only for 5 minutes before \nmoving on to the next target. Nmap will not wait more than 1.25 seconds for \na response.\n•\t\ninsane (5): In this mode, Nmap will scan a given host for only 75 seconds \nbefore moving on to the the next target. Nmap will not wait for more than 0.3 \nseconds for a response.\nIn our experience, the default timing mode usually works great unless you want to \nhave a more stealthy or faster scan.\nNmap useful options\nIn this section, we will discuss several Nmap options that are quite useful when \ndoing a penetration testing job.\nService version detection\nNmap can also be asked to check the service version when doing port scanning. \nThis information is very useful when you do the vulnerability identification process \nlater on.\nTo use this feature, give Nmap the -sV option.\nThe following is an example for this feature's usage. We want to find the software \nversion used on port 22:\nnmap -sV 192.168.56.103 -p 22\nThe following is the result of this command:\nNmap scan report for 192.168.56.103\nHost is up (0.0016s latency).\nPORT STATE SERVICE VERSION\n22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)\nFrom the preceding information, we know that on port 22, there is an SSH service \nusing the OpenSSH software Version 4.7p1 and the SSH protocol is 2.0.\n" }, { "page_number": 184, "text": "Chapter 6\n[ 163 ]\nOperating system detection\nNmap can also be asked to check the operating system used on the target machine. \nThis information is very useful when you do the vulnerability identification process \nlater on.\nTo use this feature, give Nmap the -O option.\nThe following is an example for this feature's usage. We want to find the operating \nsystem used on the target machine:\nnmap -O 192.168.56.103\nThe following command lines are the result of this command:\nHost is up (0.0037s latency).\nNot shown: 977 closed ports\nPORT STATE SERVICE\n21/tcp open ftp\n22/tcp open ssh\n23/tcp open telnet\n25/tcp open smtp\n53/tcp open domain\n80/tcp open http\n111/tcp open rpcbind\n139/tcp open netbios-ssn\n445/tcp open microsoft-ds\n512/tcp open exec\n513/tcp open login\n514/tcp open shell\n1099/tcp open rmiregistry\n1524/tcp open ingreslock\n2049/tcp open nfs\n2121/tcp open ccproxy-ftp\n3306/tcp open mysql\n5432/tcp open postgresql\n5900/tcp open vnc\n6000/tcp open X11\n6667/tcp open irc\n8009/tcp open ajp13\n" }, { "page_number": 185, "text": "Enumerating Target\n[ 164 ]\n8180/tcp open unknown\nMAC Address: 08:00:27:43:15:18 (Cadmus Computer Systems)\nDevice type: general purpose\nRunning: Linux 2.6.X\nOS CPE: cpe:/o:linux:linux_kernel:2.6\nOS details: Linux 2.6.9 - 2.6.33\nNetwork Distance: 1 hop\nBased on the preceding information, we can see that the remote system is a \nLinux operating system using Linux kernel Version 2.6.9 - 2.6.33. If there are \nvulnerabilities on those Linux kernels, we can exploit them.\nDisabling host discovery\nIf a host is blocking a ping request, Nmap may detect that the host is not active; so, \nNmap may not perform heavy probing, such as port scanning, version detection, and \noperating system detection. To overcome this, Nmap has a feature for disabling host \ndiscovery. With this option, Nmap will assume that the target machine is available \nand will perform heavy probing against that machine.\nThis option is activated by using the -Pn option.\nAggressive scan\nIf you use the -A option, it will enable the following probe:\n•\t\nService version detection (-sV)\n•\t\nOperating system detection (-O)\n•\t\nScript scanning (-sC)\n•\t\nTraceroute (--traceroute)\nIt may take some time for this scan type to finish. The following command can be \nused for aggressive scanning:\nnmap -A 192.168.56.103\nThe following is the result of this command:\nPORT STATE SERVICE VERSION\n21/tcp open ftp vsftpd 2.3.4\n|_ftp-anon: Anonymous FTP login allowed (FTP code 230)\n22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)\n| ssh-hostkey: 1024 60:0f:cf:e1:c0:5f:6a:74:d6:90:24:fa:c4:d5:6c:cd (DSA)\n" }, { "page_number": 186, "text": "Chapter 6\n[ 165 ]\n|_2048 56:56:24:0f:21:1d:de:a7:2b:ae:61:b1:24:3d:e8:f3 (RSA)\n80/tcp open http Apache httpd 2.2.8 ((Ubuntu) DAV/2)\n|_http-methods: No Allow or Public header in OPTIONS response (status \ncode 200)\n|_http-title: Metasploitable2 – Linux\n...\nHost script results:\n|_nbstat: NetBIOS name: METASPLOITABLE, NetBIOS user: , NetBIOS \nMAC: \n| smb-os-discovery: \n| OS: Unix (Samba 3.0.20-Debian)\n| NetBIOS computer name: \n| Workgroup: WORKGROUP\n|_ System time: 2013-07-21T09:20:22-04:00\nTRACEROUTE\nHOP RTT ADDRESS\n1 1.66 ms 192.168.56.103\nNmap for scanning the IPv6 target\nIn the previous section, we discussed that you can specify an IPv6 target in Nmap. In \nthis section, we will discuss this in depth.\nFor this scenario, the following is the IPv6 address of each machine involved:\n•\t\nTarget machine: fe80::a00:27ff:fe43:1518\nTo scan an IPv6 target, just use the -6 option and define the IPv6 target address. \nCurrently, you can only specify individual IPv6 addresses. The following is a sample \ncommand to do port scanning to the IPv6 address:\nnmap -6 fe80::a00:27ff:fe43:1518\nThe following is the result of this command:\nNmap scan report for fe80::a00:27ff:fe43:1518\nHost is up (0.0014s latency).\nNot shown: 996 closed ports\nPORT STATE SERVICE\n22/tcp open ssh\n" }, { "page_number": 187, "text": "Enumerating Target\n[ 166 ]\n53/tcp open domain\n2121/tcp open ccproxy-ftp\n5432/tcp open postgresql\nMAC Address: 08:00:27:43:15:18 (Cadmus Computer Systems)\nNmap done: 1 IP address (1 host up) scanned in 0.34 seconds\nWe can see that in IPv6 testing, the number of ports open are lesser compared to the \nIPv4 testing. This may be caused by the services on the remote machine that do not \nsupport IPv6 yet.\nThe Nmap scripting engine\nAlthough Nmap itself has already become a powerful network exploration tool, \nwith the additional scripting engine capabilities, Nmap becomes a much more \npowerful tool. With the Nmap Scripting Engine (NSE), users can automate various \nnetworking tasks, such as checking for new security vulnerabilities in applications, \ndetecting application versions, or other capabilities not available in Nmap. Nmap has \nalready included various NSE scripts in its package, but users can also write their \nown scripts to suit their needs.\nThe NSE scripts utilize the Lua programming language (http://www.lua.\norg) embedded in Nmap, and currently, the NSE scripts are categorized into the \nfollowing:\n•\t\nauth: The scripts in this category are used to find the authentication set on \nthe target system such as using the brute force technique.\n•\t\ndefault: These scripts are run by using the -sC or -A options. A script will \nbe grouped in the default category if it satisfies the following requirements:\n°°\nIt must be fast\n°°\nIt needs to produce valuable and actionable information\n°°\nIts output needs to be verbose and concise\n°°\nIt must be reliable\n°°\nIt should not be intrusive to the target system\n°°\nIt should divulge information to the third party\n" }, { "page_number": 188, "text": "Chapter 6\n[ 167 ]\n•\t\ndiscovery: These scripts are used to find the network.\n•\t\ndoS: The scripts in this category may cause Denial of Service (DoS) on the \ntarget system. Please use them carefully.\n•\t\nexploit: These scripts will exploit security vulnerabilities on the target \nsystem. The penetration tester needs to have permission to run these scripts \non the target system.\n•\t\nexternal: These scripts may divulge information to third parties.\n•\t\nfuzzer: These scripts are used to do fuzzing to the target system.\n•\t\nintrusive: These scripts may crash the target system or use all of the target \nsystem resources.\n•\t\nmalware: These scripts will check for the existence of malware or backdoors \non the target system.\n•\t\nsafe: These scripts are not supposed to cause a service crash, Denial of \nService (DoS), or exploit target system.\n•\t\nversion: These scripts are used with the version detection option (-sV) to \ncarry out advanced detection for the service on the target system.\n•\t\nvuln: These scripts are used to check for security vulnerabilities on the \ntarget system.\nIn Kali Linux, these Nmap scripts are located in the /usr/share/nmap/scripts \ndirectories, and currently, Nmap Version 6.25 included with Kali Linux contains \nmore than 430 scripts.\nThere are several command-line arguments that can be used to call NSE as follows:\n•\t\n-sC or --script=default: This performs scan using default scripts.\n•\t\n--script | | : This performs \nscan using the script defined in filename, categories, or directories.\n•\t\n--script-args : This provides script argument. An example of these \narguments are username or password if you use the auth category.\n" }, { "page_number": 189, "text": "Enumerating Target\n[ 168 ]\nTo do port scanning to the host 192.168.56.103 and utilize the default script \ncategories, we can give the following command:\nnmap -sC 192.168.56.103\nThe following is the result snippet:\nNmap scan report for 192.168.56.103\nNot shown: 977 closed ports\nPORT STATE SERVICE\n21/tcp open ftp\n|_ftp-anon: Anonymous FTP login allowed (FTP code 230)\n22/tcp open ssh\n| ssh-hostkey: 1024 60:0f:cf:e1:c0:5f:6a:74:d6:90:24:fa:c4:d5:6c:cd (DSA)\n|_2048 56:56:24:0f:21:1d:de:a7:2b:ae:61:b1:24:3d:e8:f3 (RSA)\n25/tcp open smtp\n|_smtp-commands: metasploitable.localdomain, PIPELINING, SIZE 10240000, \nVRFY, ETRN, STARTTLS, ENHANCEDSTATUSCODES, 8BITMIME, DSN, \n| ssl-cert: Subject: commonName=ubuntu804-base.localdomain/\norganizationName=OCOSA/stateOrProvinceName=There is no such thing outside \nUS/countryName=XX\n| Not valid before: 2010-03-17T14:07:45+00:00\n|_Not valid after: 2010-04-16T14:07:45+00:00\n|_ssl-date: 2013-07-21T08:40:20+00:00; -4s from local time.\n53/tcp open domain\n| dns-nsid: \n|_ bind.version: 9.4.2\n111/tcp open rpcbind\n| rpcinfo: \n| program version port/proto service\n| 100000 2 111/tcp rpcbind\n| 100000 2 111/udp rpcbind\n| 100003 2,3,4 2049/tcp nfs\n| 100003 2,3,4 2049/udp nfs\n| 100005 1,2,3 35075/udp mountd\n| 100005 1,2,3 59685/tcp mountd\n| 100021 1,3,4 37466/tcp nlockmgr\n| 100021 1,3,4 60726/udp nlockmgr\n| 100024 1 36880/udp status\n" }, { "page_number": 190, "text": "Chapter 6\n[ 169 ]\n|_ 100024 1 38557/tcp status\n3306/tcp open mysql\n| mysql-info: Protocol: 10\n| Version: 5.0.51a-3ubuntu5\n| Thread ID: 7\n| Some Capabilities: Connect with DB, Compress, SSL, Transactions, Secure \nConnection\n| Status: Autocommit\n|_Salt: !`BijWW-x7HCVi,<*[l-\n5900/tcp open vnc\n| vnc-info: \n| Protocol version: 3.3\n| Security types:\n|_ Unknown security type (33554432)\n6667/tcp open irc\n| irc-info: Server: irc.Metasploitable.LAN\n| Version: Unreal3.2.8.1. irc.Metasploitable.LAN \n| Lservers/Lusers: 0/1\n| Uptime: 0 days, 0:15:26\n| Source host: 50388A6E.97684684.FFFA6D49.IP\n|_Source ident: OK nmap\n8180/tcp open unknown\n|_http-favicon: Apache Tomcat\n|_http-methods: No Allow or Public header in OPTIONS response (status \ncode 200)\n|_http-title: Apache Tomcat/5.5\nMAC Address: 08:00:27:43:15:18 (Cadmus Computer Systems)\nHost script results:\n|_nbstat: NetBIOS name: METASPLOITABLE, NetBIOS user: , NetBIOS \nMAC: \n| smb-os-discovery: \n| OS: Unix (Samba 3.0.20-Debian)\n| NetBIOS computer name: \n| Workgroup: WORKGROUP\n|_ System time: 2013-07-21T04:40:20-04:00\nNmap done: 1 IP address (1 host up) scanned in 46.87 seconds\n" }, { "page_number": 191, "text": "Enumerating Target\n[ 170 ]\nFrom the preceding information, you can see that now the Nmap result is more \nthorough. This is because it utilizes the NSE default scripts.\nHowever, if you only want specific information on the target system, you can use the \nscript by itself. If we want to collect information about the HTTP server, we can use \nseveral HTTP scripts in NSE, such as http-enum, http-headers, http-methods, and \nhttp-php-version using the following command:\nnmap --script http-enum,http-headers,http-methods,http-php-version -p 80 \n192.168.56.103\nThe following is the result of this command:\nNmap scan report for 192.168.56.103\nHost is up (0.0010s latency).\nPORT STATE SERVICE\n80/tcp open http\n| http-enum: \n| /tikiwiki/: Tikiwiki\n| /test/: Test page\n| /phpinfo.php: Possible information file\n| /phpMyAdmin/: phpMyAdmin\n| /doc/: Potentially interesting directory w/ listing on 'apache/2.2.8 \n(ubuntu) dav/2'\n| /icons/: Potentially interesting folder w/ directory listing\n|_ /index/: Potentially interesting folder\n| http-headers: \n| Date: Sun, 21 Jul 2013 08:45:07 GMT\n| Server: Apache/2.2.8 (Ubuntu) DAV/2\n| X-Powered-By: PHP/5.2.4-2ubuntu5.10\n| Connection: close\n| Content-Type: text/html\n| \n|_ (Request type: HEAD)\n|_http-methods: No Allow or Public header in OPTIONS response (status \ncode 200)\n| http-php-version: Versions from logo query (less accurate): 5.1.3 - \n5.1.6, 5.2.0 - 5.2.17\n| Versions from credits query (more accurate): 5.2.3 - 5.2.5\n" }, { "page_number": 192, "text": "Chapter 6\n[ 171 ]\n|_Version from header x-powered-by: PHP/5.2.4-2ubuntu5.10\nMAC Address: 08:00:27:43:15:18 (Cadmus Computer Systems)\nNmap done: 1 IP address (1 host up) scanned in 24.47 seconds\nBy utilizing four NSE scripts related to HTTP, we gain more information regarding \nthe target system's web server:\n•\t\nThere are several interesting directories to check: Tikiwiki, test, \nand phpMyAdmin\n•\t\nWe have an interesting file: phpinfo.php\n•\t\nWe know the server is using PHP Version 5.2.3 -5.2.5\nAfter discussing Nmap, let's discuss another port scanner tool.\nThere is a useful NSE script called Nmap NSE Vulscan (http://www.computec.\nch/mruef/software/nmap_nse_vulscan-1.0.tar.gz) that can help you to map \nthe version information you obtain from a target machine with the vulnerability \ndatabase, such as CVE (http://cve.mitre.org/), OSVDB (http://www.osvdb.\norg/), scip VulDB (http://www.scip.ch/?vuldb), SecurityTracker (http://\nsecuritytracker.com/), and SecurityFocus (http://www.securityfocus.com/).\nThe following screenshot shows the sample result of the CVE script:\n" }, { "page_number": 193, "text": "Enumerating Target\n[ 172 ]\nNmap options for Firewall/IDS evasion\nDuring penetration testing, you may encounter a system that is using firewall and \nIDS to protect the system. If you just use the default settings, your action may get \ndetected or you may not get the correct result from Nmap. The following options \nmay be used to help you evade the firewall/IDS:\n•\t\n-f (fragment packets): This purpose of this option is to make it harder to \ndetect the packets. By specifying this option once, Nmap will split the packet \ninto 8 bytes or less after the IP header.\n•\t\n--mtu: With this option, you can specify your own packet size fragmentation. \nThe Maximum Transmission Unit (MTU) must be a multiple of eight or \nNmap will give an error and exit.\n•\t\n-D (decoy): By using this option, Nmap will send some of the probes from \nthe spoofed IP addresses specified by the user. The idea is to mask the true IP \naddress of the user in the logfiles. The user IP address is still in the logs. You \ncan use RND to generate a random IP address or RND:number to generate the \n IP address. The hosts you use for decoys should be up, or you will \nflood the target. Also remember that by using many decoys you can cause \nnetwork congestion, so you may want to avoid that especially if you are \nscanning your client network.\n•\t\n--source-port or –g (spoof source port): This option will be \nuseful if the firewall is set up to allow all incoming traffic that comes from a \nspecific port.\n•\t\n--data-length: This option is used to change the default data length sent by \nNmap in order to avoid being detected as Nmap scans.\n•\t\n--max-parallelism: This option is usually set to one in order to instruct \nNmap to send no more than one probe at a time to the target host.\n•\t\n--scan-delay