Violent Python
Total Page:16
File Type:pdf, Size:1020Kb
Violent Python A Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers Violent Python A Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers TJ. O’Connor !-34%2$!-s"/34/.s(%)$%,"%2's,/.$/. .%79/2+s/8&/2$s0!2)3s3!.$)%'/ 3!.&2!.#)3#/s3).'!0/2%s39$.%9s4/+9/ 3YNGRESSISAN)MPRINTOF%LSEVIER Acquiring Editor: Chris Katsaropoulos Development Editor: Meagan White Project Manager: Priya Kumaraguruparan Designer: Russell Purdy Syngress is an imprint of Elsevier 225 Wyman Street, Waltham, MA 02451, USA Copyright © 2013 Elsevier, Inc. All rights reserved. No part of this publication may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or any information storage and retrieval system, without permission in writing from the publisher. Details on how to seek permission, further information about the Publisher’s permissions policies and our arrange- ments with organizations such as the Copyright Clearance Center and the Copyright Licensing Agency, can be found at our website: www.elsevier.com/permissions. This book and the individual contributions contained in it are protected under copyright by the Publisher (other than as may be noted herein). Notices Knowledge and best practice in this !eld are constantly changing. As new research and experi- ence broaden our understanding, changes in research methods or professional practices, may become necessary. Practitioners and researchers must always rely on their own experience and knowledge in evaluating and using any information or methods described herein. In using such information or methods they should be mindful of their own safety and the safety of others, including parties for whom they have a professional responsibility. To the fullest extent of the law, neither the Publisher nor the authors, contributors, or editors, assume any liability for any injury and/or damage to persons or property as a matter of products liability, negligence or otherwise, or from any use or operation of any methods, products, instructions, or ideas contained in the material herein. Library of Congress Cataloging-in-Publication Data Application submitted British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library. ISBN: 978-1-59749-957-6 Printed in the United States of America 13 14 15 10 9 8 7 6 5 4 3 2 1 For information on all Syngress publications visit our website at www.syngress.com Trademarks %LSEVIER )NC THEAUTHORS ANDANYPERSONORlRMINVOLVEDINTHEWRITING EDITING ORPRODUCTIONCOLLECTIVELYh-AKERSv OFTHISBOOKhTHE7ORKv DO NOTGUARANTEEORWARRANTTHERESULTSTOBEOBTAINEDFROMTHE7ORK 4HEREISNOGUARANTEEOFANYKIND EXPRESSEDORIMPLIED REGARDINGTHE7ORKOR ITSCONTENTS4HE7ORKISSOLD!3)3AND7)4(/547!22!.499OUMAYHAVE OTHERLEGALRIGHTS WHICHVARYFROMSTATETOSTATE )NNOEVENTWILL-AKERSBELIABLETOYOUFORDAMAGES INCLUDINGANYLOSSOF PROlTS LOSTSAVINGS OROTHERINCIDENTALORCONSEQUENTIALDAMAGESARISINGOUT FROMTHE7ORKORITSCONTENTS"ECAUSESOMESTATESDONOTALLOWTHEEXCLUSION ORLIMITATIONOFLIABILITYFORCONSEQUENTIALORINCIDENTALDAMAGES THEABOVE LIMITATIONMAYNOTAPPLYTOYOU 9OUSHOULDALWAYSUSEREASONABLECARE INCLUDINGBACKUPANDOTHERAPPROPRI- ATEPRECAUTIONS WHENWORKINGWITHCOMPUTERS NETWORKS DATA ANDlLES 3YNGRESS -EDIA 3YNGRESS h#AREER !DVANCEMENT 4HROUGH 3KILL %NHANCE- MENT v h!SK THE !UTHOR 50$!4% v AND h(ACK 0ROOlNG v ARE REGISTERED TRADEMARKS OF %LSEVIER )NCh3YNGRESS4HE $ElNITION OF A 3ERIOUS 3ECURITY ,IBRARYv4- h-ISSION#RITICAL4- vANDh4HE/NLY7AYTO3TOPA(ACKERISTO 4HINK,IKE/NE4-vARETRADEMARKSOF%LSEVIER )NC"RANDSANDPRODUCTNAMES MENTIONED IN THIS BOOK ARE TRADEMARKS OR SERVICE MARKS OF THEIR RESPECTIVE COMPANIES v Dedication For my monkey and my ninja princess: anything is possible if you try hard enough. ix Lead Author – TJ O’Connor 4*/#ONNORISA$EPARTMENTOF$EFENSEEXPERTONINFORMATIONSECURITYAND A 53 !RMY PARATROOPER 7HILE ASSIGNED AS AN ASSISTANT PROFESSOR AT THE 53 -ILITARY !CADEMY 4* TAUGHT UNDERGRADUATE COURSES ON FORENSICS EXPLOITA- TION AND INFORMATION ASSURANCE (E TWICE CO COACHED THE WINNING TEAM AT THE .ATIONAL 3ECURITY !GENCYS ANNUAL #YBER $EFENSE %XERCISE AND WON THE .ATIONAL$EFENSE5NIVERSITYSlRSTANNUAL#YBER#HALLENGE(EHASSERVEDON MULTIPLEREDTEAMS INCLUDINGTWICEONTHE.ORTHEAST2EGIONAL4EAMFORTHE .ATIONAL#OLLEGIATE#YBER$EFENSE#OMPETITION 4*HOLDSA-ASTEROF3CIENCEDEGREEIN#OMPUTER3CIENCEFROM.ORTH#AROLINA 3TATE A -ASTER OF 3CIENCE DEGREE IN )NFORMATION 3ECURITY %NGINEERING FROM THE3!.34ECHNICAL)NSTITUTE ANDA"ACHELOROF3CIENCEDEGREEIN#OMPUTER 3CIENCEFROMTHE53-ILITARY!CADEMY(EHASPUBLISHEDTECHNICALRESEARCHAT 53%.)8WORKSHOPS !#-CONFERENCES SECURITYCONFERENCES THE3!.32EAD- ING2OOM THE)NTERNET3TORM#ENTER THEArmy Magazine ANDTHEArmed Forces Journal(EHOLDSEXPERTCYBERSECURITYCREDENTIALS INCLUDINGTHEPRESTIGIOUS ')!#3ECURITY%XPERT'3% AND/FFENSIVE3ECURITY#ERTIlED%XPERT/3#% 4*ISAMEMBEROFTHEELITE3!.32EDAND"LUE4EAM#YBER'UARDIANS xvii Contributing Author Bio – Rob Frost 2OBERT &ROST GRADUATED FROM THE 5NITED 3TATES -ILITARY !CADEMY IN COMMISSIONINGINTOTHE!RMY3IGNAL#ORPS(EHOLDSA"ACHELOROF3CIENCE DEGREE IN #OMPUTER 3CIENCE WITH HONORS WITH HIS THESIS WORK FOCUSING ON OPEN SOURCEINFORMATION GATHERING2OBWASINDIVIDUALLYRECOGNIZEDASONEOF THETOPTWOMEMBERSOFTHENATIONALCHAMPIONSHIPTEAMFORTHE#YBER $EFENSE%XERCISEDUETOHISABILITYTOCIRCUMVENTRULES2OBHASPARTICIPATEDIN ANDWONSEVERALCYBERSECURITYCOMPETITIONS xix Technical Editor Bio – Mark Baggett -ARK"AGGETTISA#ERTIlED3!.3)NSTRUCTORANDTEACHESSEVERALCOURSESINTHE 3!.3 PENETRATION TESTING CURRICULUM -ARK IS THE PRIMARY CONSULTANT AND FOUNDER OF )N $EPTH $EFENSE )NC WHICH PROVIDES INCIDENT RESPONSE AND PENETRATION TESTINGSERVICES4ODAY INHISROLEASTHETECHNICALADVISORTOTHE $EPARTMENTOF$EFENSEFOR3!.3 -ARKISFOCUSEDONTHEPRACTICALAPPLICATION OF3!.3RESOURCESINTHEDEVELOPMENTOFMILITARYCAPABILITIES -ARKHASHELDAVARIETYOFPOSITIONSININFORMATIONSECURITYFORLARGEINTERNA- TIONALAND&ORTUNECOMPANIES(EHASBEENASOFTWAREDEVELOPER ANET- WORKANDSYSTEMSENGINEER ASECURITYMANAGER ANDA#)3/!SA#)3/ -ARK WASRESPONSIBLEFORPOLICY COMPLIANCE INCIDENTRESPONSE ANDALLOTHERASPECTS OFINFORMATIONSECURITYOPERATIONS-ARKKNOWSlRSTHANDTHECHALLENGESTHAT INFORMATION SECURITY PROFESSIONALS FACE TODAY IN SELLING IMPLEMENTING AND SUPPORTINGINFORMATIONSECURITY-ARKISANACTIVEMEMBEROFTHEINFORMATION SECURITYCOMMUNITYANDTHEFOUNDINGPRESIDENTOFTHE'REATER!UGUSTA)33! (EHOLDSSEVERALCERTIlCATIONS INCLUDING3!.3PRESTIGIOUS'3%-ARKBLOGS ABOUTVARIOUSSECURITYTOPICSATHTTPWWWPAULDOTCOMCOM xxi Introduction 0YTHONISAHACKERSLANGUAGE7ITHITSDECREASEDCOMPLEXITY INCREASEDEFl- CIENCY LIMITLESSTHIRD PARTYLIBRARIES ANDLOWBARTOENTRY 0YTHONPROVIDESAN EXCELLENTDEVELOPMENTPLATFORMTOBUILDYOUROWNOFFENSIVETOOLS)FYOUARE RUNNING-AC/38OR,INUX ODDSAREITISALREADYINSTALLEDONYOURSYSTEM 7HILEAWEALTHOFOFFENSIVETOOLSALREADYEXIST LEARNING0YTHONCANHELPYOU WITHTHEDIFlCULTCASESWHERETHOSETOOLSFAIL TARGET AUDIENCE %VERYONELEARNSDIFFERENTLY(OWEVER WHETHERYOUAREABEGINNERWHOWANTS TOLEARNHOWTOWRITE0YTHON ORANADVANCEDPROGRAMMERWHOWANTSTOLEARN HOWTOAPPLYYOURSKILLSINPENETRATIONTESTING THISBOOKISFORYOU ORGANIZATION OF THE BOOK )NWRITINGTHISBOOK WEREALLYSETOUTTOWRITEANEVILCOOKBOOKOFEXAMPLES FOR THE DARKER SIDE OF 0YTHON 4HE FOLLOWING PAGES PROVIDE 0YTHON RECIPES FORPENETRATIONTESTING WEBANALYSIS NETWORKANALYSIS FORENSICANALYSIS AND EXPLOITINGWIRELESSDEVICES(OPEFULLY THEEXAMPLESWILLINSPIRETHEREADERTO CREATEHISORHEROWN0YTHONSCRIPTS Chapter 1: Introduction )FYOUHAVENOTPROGRAMMEDIN0YTHONBEFORE #HAPTERPROVIDESBACKGROUND INFORMATION ABOUT THE LANGUAGE VARIABLES DATA TYPES FUNCTIONS ITERATION SELECTION ANDWORKINGWITHMODULES ANDMETHODICALLYWALKSTHROUGHWRIT- INGAFEWSIMPLEPROGRAMS&EELFREETOSKIPITIFYOUAREALREADYCOMFORTABLE WITHTHE0YTHONPROGRAMMINGLANGUAGE!FTERTHElRSTCHAPTER THEFOLLOWING SIXCHAPTERSAREFAIRLYINDEPENDENTFROMONEANOTHERFEELFREETOREADTHEMIN WHICHEVERORDERYOUPLEASE ACCORDINGTOWHATSTRIKESYOURCURIOSITY xxiii xxiv Introduction Introduction Chapter 2: Penetration Testing with Python #HAPTER INTRODUCES THE IDEA OF USING THE 0YTHON PROGRAMMING LANGUAGE TOSCRIPTATTACKSFORPENETRATIONTESTING4HEEXAMPLESINTHECHAPTERINCLUDE BUILDINGAPORTSCANNER CONSTRUCTINGAN33(BOTNET MASS COMPROMISINGVIA &40 REPLICATING#ONlCKER ANDWRITINGANEXPLOIT Chapter 3: Forensic Investigations with Python #HAPTERUTILIZES0YTHONFORDIGITALFORENSICINVESTIGATIONS4HISCHAPTERPRO- VIDESEXAMPLESFORGEO LOCATINGINDIVIDUALS RECOVERINGDELETEDITEMS EXTRACT- INGARTIFACTSFROMTHE7INDOWSREGISTRY EXAMININGMETADATAINDOCUMENTSAND IMAGES ANDINVESTIGATINGAPPLICATIONANDMOBILEDEVICEARTIFACTS Chapter 4: Network Traffic Analysis with Python #HAPTERUSES0YTHONTOANALYZENETWORKTRAFlC4HESCRIPTSINTHISCHAPTER GEO LOCATE)0ADDRESSESFROMPACKETCAPTURES INVESTIGATEPOPULAR$$O3TOOL- KITS DISCOVERDECOYSCANS ANALYZEBOTNETTRAFlC ANDFOILINTRUSIONDETECTION SYSTEMS Chapter 5: Wireless Mayhem with Python #HAPTERCREATESMAYHEMFORWIRELESSAND"LUETOOTHDEVICES4HEEXAMPLESIN THISCHAPTERSHOWHOWTOSNIFFANDPARSEWIRELESSTRAFlC BUILDAWIRELESSKEY- LOGGER IDENTIFYHIDDENWIRELESSNETWORKS REMOTELYCOMMAND5!6S IDENTIFY MALICIOUS WIRELESS TOOLKITS IN USE STALK "LUETOOTH RADIOS AND EXPLOIT "LUE- TOOTHVULNERABILITIES Chapter 6: Web Recon With Python #HAPTER EXAMINES USING 0YTHON TO SCRAPE THE WEB FOR INFORMATION 4HE EXAMPLESINTHISCHAPTERINCLUDEANONYMOUSLYBROWSINGTHEWEBVIA0YTHON WORKINGWITHDEVELOPER!0)S SCRAPINGPOPULARSOCIALMEDIASITES ANDCREATING ASPEAR PHISHINGEMAIL Chapter 7: Antivirus Evasion with Python )NTHE&INALCHAPTER #HAPTER WEBUILDAPIECEOFMALWARETHATEVADESANTIVI- RUSSYSTEMS!DDITIONALLY WEBUILDASCRIPTFORUPLOADINGOURMALWAREAGAINST ANONLINEANTIVIRUSSCANNER