Hacking with Python - index-of.esindex-of.es/Varios-2/Hacking with Python The Ultimate Beginner's...

Post on 24-May-2020

99 views 8 download

transcript

HackingwithPython

TheUltimateBeginner’sGuide

IntroductionThisbookwillshowyouhowtousePython,createyourownhackingtools,andmakethemostoutofavailableresourcesthataremadeusingthisprogramminglanguage.Ifyoudonothaveexperienceinprogramming,don’tworry–thisbookwillshowguideyouthroughunderstandingthebasicconceptsofprogrammingandnavigatingPythoncodes.Thisbookwillalsoserveasyourguideinunderstandingcommonhackingmethodologiesandinlearninghowdifferenthackersusethemforexploitingvulnerabilitiesorimprovingsecurity.YouwillalsobeabletocreateyourownhackingscriptsusingPython,usemodulesandlibrariesthatareavailablefromthird-partysources,andlearnhowtotweakexistinghackingscriptstoaddressyourowncomputingneeds.ThankyouandIhopeyouenjoyit!

Copyright2017bySteveTaleAllrightsreserved.

Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothetopicand issue covered. The publication is sold with the idea that the publisher is not required torenderaccounting,officiallypermitted,orotherwise,qualifiedservices. Ifadvice isnecessary,legalorprofessional,a21practicedindividualintheprofessionshouldbeordered.-FromaDeclarationofPrincipleswhichwasacceptedandapprovedequallybyaCommitteeoftheAmericanBarAssociationandaCommitteeofPublishersandAssociations.In no way is it legal to reproduce, duplicate, or transmit any part of this document in eitherelectronicmeansorinprintedformat.Recordingofthispublicationisstrictlyprohibitedandanystorageof thisdocument isnot allowedunlesswithwrittenpermission from thepublisher.Allrightsreserved.The information provided herein is stated to be truthful and consistent, in that any liability, intermsofinattentionorotherwise,byanyusageorabuseofanypolicies,processes,ordirectionscontained within is the solitary and utter responsibility of the recipient reader. Under nocircumstances will any legal responsibility or blame be held against the publisher for anyreparation,damages,ormonetarylossduetotheinformationherein,eitherdirectlyorindirectly.Respectiveauthorsownallcopyrightsnotheldbythepublisher.Theinformationhereinisofferedforinformationalpurposessolely,andisuniversalasso.Thepresentationoftheinformationiswithoutcontractoranytypeofguaranteeassurance.The trademarks that are used arewithout any consent, and the publication of the trademark iswithout permission or backing by the trademark owner.All trademarks and brandswithin thisbookareforclarifyingpurposesonlyandaretheownedbytheownersthemselves,notaffiliatedwiththisdocument.

TableofcontentsChapter1:PreparationForHacking

Chapter2:PythonBasics

Chapter3:WritingPythonPrograms

Chapter5:OperatorsandExpressions

Chapter6:FunctionsandModules

Chapter7:SettingUpforHacking

Chapter8:NetworkHacking

Chapter9:HacksfortheWeb

Chapter10:UnderstandingAttacksUsingPython

Chapter11:OtherNiftyHackstoTry

Conclusion

Bonus:PreviewOf‘IntroductiontoPython3

Chapter1:PreparationforhackingEveryaspiringhackershouldlearnhowtouseaprogramminglanguageinordertodiscoverandexploitweaknessesinacomputer.Whilethereisnothingwrongwithusingresourcesthatarealreadymadeavailable,youwillwanttodevelopbettertoolsthatcanallowyoutomakebetteruseofyourowncomputer.Becauseyouarethebestjudgewhenitcomestounderstandingyourownneeds,youareawarethatmanyoftheexistingtoolsavailableonlineorinthemarketlacksomeofthefeaturesthatyoumayneedtomakeyourcomputerperformjustthewayyouwantit.

Thecomputingworldchangeseveryday–newhacksaredevelopedbythehourandyoucanalsoexpectthatdifferentsecurityexpertsdiscoverthem.Ifyouarestuckonusingoldhackingtoolstoeitherperformreconnaissanceorprotectyourselffromapossibilityofanattack,thenyouarelikelytorunintosometrouble.Forexample,launchingamalwareonatargetedmachinethathasalreadyimproveditssecuritysystemwillnotonlycauseyourattacktofail–thelikelihoodoftheattackbeingtracedbacktoyouisalsohigh.

LearningaprogramminglanguagewillalsoallowyoutoincreaseyourprobabilityofhackingsuccessanddecreasethelikelihoodofgettingdetectedbyIDS(intrusiondetectionsystems),antivirussoftware,ortoolsthatareusedbylawenforcement.Ifyouarelearninghowtobeawhitehathackerbylearninghowcriminalhackersactanddeveloptheirowntoolsforsystemexploitationandmanipulation,thenyouwilldefinitelybeabletouseupdatedsecuritycodestocombatnewcrackingprogramsthataredevelopedeveryday.Bybeingabletocodeprogramsonthego,youwillalsobeabletodetectandpreventattacksastheyhappen.

Beingabletocodeyourownhackingtoolswillalsoallowyoutocontributetothecommunityofhackersthataresharingtheirresourceswithyou–bydiscoveringabetterwaytoperformanattack,doacountermeasureagainstanillegalhack,orupdatesecurityprotocolsorabilitiesofaknowntool,youwillbeabletodoyourshareinmakingthecomputingworldamoresecureplacetobein.

WhatisPython?Pythonisconsideredanopensourcelanguage,whichmeansthatyoucandownloaditfromthepython.org’swebsitefreeofcharge.Thishigh-levellanguagehasbeenaroundsincethelate‘80s,buthasdefinitelysurvivedthetestoftime–itisstillusedtodaytocreateGUIs,webapps,games,andmoreimportantly,hackingexploitsandintrusionmitigation.

Ifyouaremigratingfromanotherprogramminglanguage,youwillbeabletoeasilylearnPythonthankstoitseasyreadability.MostofthecommandsusetypicalEnglishstatementswhichwillallowyoutoimmediatelyunderstandtheirpurposeevenifitisthefirsttimethatyouhaveencounteredthislanguage.Pythoncodesarealsosomuchshorterandsimplercomparedtootherhigh-levellanguagessuchasJava,andcomeswithalibraryandfeaturesthatarealreadybuilt-in,aswellasaccesstothird-partymodulesandlibraries.Itsrobustintegratedlibrariesandtheavailabilityofresourcesthatarecompiledbyotherusersmakeitoneofthefavoriteprogramminglanguagesofhackers.

Here’sanexample:ifyouwanttoperformtheclassicPrintcommandtotypeout“Hello,World!”usingJava,youwillhavetotypeoutthefollowing:

However,Pythonwilljustrequireyoutokeyinthefollowing:

Atthispoint,yougettheideathatacompletehackingscriptwillbemuchsimplerandshorterusingPython,comparedtootherhigh-levellanguagesthataretypicallyusedforcreatingprograms.

Ifyouareafirst-timeprogrammer,youwillfindPythontoberelativelyeasytolearn,thankstoitssimplercodesandsyntax.Youwillalsobeabletorunyourcodesondifferenttypesofdevicesandoperatingsystems,suchasAndroid,Windows,Linux,andMacOSX.Ifyouareinterestedinjumpingrightintohacking,youwilldefinitelyhaveendlessfundiscoveringwhatyoucanmanipulatewithyourownprograms–Pythondoesnotonlyallowyoutoexploitandmanipulatelaptops,smartphones,anddesktops,butalsoallowyoutorunyourprogramsonmicrocontrollersthatarefoundintoys,remotecontrols,appliances,andvirtuallyanydevicethathasacomputerinit.

StartingwithPythonIfyouareusingarecentLinuxorUNIXdistribution,youprobablyhavethePythoninstalledalready.SomeWindowsusers,particularlyHPcomputerowners,mayalsohaveitinstalledintheircomputers.However,ifyouneedafreshinstallofthepackage,youcandownloaditfromwww.python.org.

Normally,youwouldwanttogetthelatestversion,whichis3.5.2,butyoumayalsowanttogetthelatestreleaseofPython2,whichis2.7.11,ifitismorecompatiblewiththehackingprojectsthatyouhaveinmind.WhilePython3maybethefutureofthisprogramminglanguage,certainfactorssuchascompatibilitywithyourcomputerorusingthirdpartyservicesmaymakeyoudownloadPython2instead.

WindowsInstallationAfteryouhavedownloadedtheinstallationpackagefromtheLinuxwebsite,decompressitandrunthe.exefiletoproceedwiththesetup.Youshouldbeabletogetpip,documentation,andIDLEwhenyougowiththestandardinstallation.

Note:Seetoitthatyouhavecheckedthisoption:

Ifyouwanttochangethelocationforyourinstallation,simplyclickon

andthenhitNext.Afterwards,usethepathc:\python35asyourinstalllocation.IfyouhaveinstalledPythoninthecorrectpath,goto:

YoucanalsorunPythonfromthecommandpromptifyouhavecorrectlysetthePATHvariableuponinstallation.IfyouarerunningPythonforthefirsttimeinWindows,typecmdintheRundialogbox(clickonStartbuttontolocatethiscommand).Onceyouhavethecommandpromptpulledup,keyin“python”tolaunchtheprogram.

MacOSXInstallationYoucandownloadtheinstallerfromPython’swebsiteoryoucanuseHomebrewtogettheinstallpackage.IfyoudonothaveHomebrewinstalledyet,pullupaterminal(presstheCommandkey+SpacebartolaunchSpotlightsearch,andthenkeyinTerminal)andenterthiscommand:

/usr/bin/ruby-e"$(curl-fsSLhttps://raw.githubusercontent.com/Homebrew/install/master/install)"

AfterHomebrewisinstalled,itwillpromptyouabouthowitwillproceedwiththeinstallation.HitEnterandthenprovideyouruserpasswordinordertoproceed.Onceinstalled,youcannowusethe“brew”commandfromtheterminaltoinstallpackagesforOSX.

ToinstallthePythonpackage,pullupafreshTerminalandkeyin:

InstallingonLinuxIfyouroperatingsystemisGNU/Linux,youcanuseUbuntuorDebiandistributionmanagertoinstallPython.Todothat,simplykeyinthiscommand:

Onceyouareabletoinstalltheprogram,runitbytyping“python”ontheterminal.

InteractingwiththePythonLanguageNowthatyouhaveinstalledPython,thenextthingthatyouneedtodoistolearnhowyoucanuseittoexplorefeaturesortotestacode.YoucanusePythonusingthescriptmodeifyouwanttoseehowentirefilesorapplicationsareinterpreted.

TointeractusingPython,youcanusetheIDLE(IntegratedDevelopmentEnvironment),whichwillpullupthePythonshellwindow,orthecommandlineinWindows.

InteractingUsingtheCommandPromptTheWindowscommandline(ortheTerminalinLinuxandMacOSX)isthesimplestandstraightforwardwaytostartusingPython.Withthistool,youwillbeabletoseehowPythonoperatesbasedonhowitreactstoeverycommandthatyouenteronthe>>>prompt,whichisalsoknownastheinterpreterprompt.

Takenotethatthismightnotbethemostpreferredwaybyhackerswhenitcomestointeractingwiththisprogramminglanguage,butthismethodwillallowyoutoeasilyexplorePython’sfeatures.

ToexplorehowPythonoperates,takealookathowtheprintcommandcanbeusedtodisplay“Pythonisforhacking.”

PullupthePythoncommandline.

Onceyouseethe>>>prompt,keyin:

print(“Pythonisforhacking.”)

HitEntertoendthecommand.Rightafterthat,Pythonwilldisplayyourrequestedtextonthefollowingline.

Whatwillhappenifyoudidsomethingwrongwithyourcommand?Ifyouusedafaultysyntax,suchasanincompletestatementoramisspelledcommand,youwillgetadisplayerrorthatlookslikethis:

HowtoExitPythonIfyouwanttoquitthePythonprompt,useanyofthesecommands:

Ctrl+Z,andthenhitEnter

Keyin“quit()”

Keyin“exit()”

InteractingUsingtheIDLE

Whenyouareusingaprogramminglanguage,suchasPython,youwillneedtodevelopyourcodeusinganintegrateddevelopmentenvironmentorIDE.AnIDEisanapplicationthatwillprovideyouallthetoolsthatyouneedtodevelopasoftware.Usually,thesetoolsareatexteditorthatwillhelpyoutweakthesourcecodethatyouareworkingon,adebugger,andasetoftoolsforbuildautomationwhichyoucanusethroughaGUI(graphicaluserinterface).IDEswillalsoallowyoutouseintegrationwithversioncontrollibrariesthatyoucansourcefromthirdparties,whichmeansthatyoucanpullupcodesthatarecreatedbyothersandthenmixandmatchthemwithyourowncodetogettheresultsthatyouwant.

YoucangetyourpreferredIDEfromathird-partysource,suchaseducationalsitesforprogramminglanguages,orfromthedevelopersofthelanguagethemselves.Python.org,forexample,providesyouafreeIDEthatyoucanuseasastartingpointtodevelopment,ifyouarenotsurewhichIDEwillworkbestwithyourcodingstyle.

TheIDLEtoolthatcomeswithyourinstallationpackageservesasaplatformwhereyoucanefficientlykeyinyourcodesandinteractwithPython.YoucaneasilypullupIDLEbyclickingonitsicononyourdesktop,theStartMenuorlocatingitontheinstallfolder.

IDLEallowsyoutousethesefeatures:

ThePythonshellwindowwhichallowsyoutomakeuseofcolor-codedcodeinputandoutputandgeterrormessagesifyouinputawrongstatement.

Adebuggerthatcomeswithstepping,localandglobalnamespaceviewing,andpersistentbreakpoints

Browsersandconfiguration

Atexteditorthatallowsyoutousemultiplewindows,colorizingforPython,auto-completion,undo,andotherfeatures

UsingIDLEwillallowyoutousetwowindows(theShellandtheEditor)whichyoucanusesimultaneously.Youcanalsohaveoutputwindowsthathaveadifferentcontextmenuandtitle.

ThemenusthatyoucanuseinIDLEwillchangedependingonthewindowthatyouhaveselected.Theoptionsthatbelongtoeachmenuarestraightforward,whichmeansthatyouwillnothaveahardtimeunderstandingwhateachofthemdoevenifyouarenewtoprogramming.

Herearethemenusandthewindowthattheyareassociatedwith.

File(forEditorandShellwindows)

Thismenucontainsthefollowingoptions:

1. New

2. Open

3. RecentFiles

4. OpenModule

5. ClassBrowser

6. PathBrowser

7. Save

8. SaveAs

9. SaveCopyAs

10. PrintWindow

11. Close

12. Exit

Edit(forEditorandShell)

Thismenucontainsthefollowingoptions:

1. Undo

2. Redo

3. Cut

4. Copy

5. Paste

6. SelectAll

7. Find

8. FindAgain

9. FindSelection

10. FindinFiles

11. Replace

12. GotoLine

13. ShowCompletions

14. ExpandWord

15. ShowCallTip

16. ShowSurroundingParens

Format(EditorWindow)

1. IndentRegion

2. DedentRegion

3. CommentOutRegion

4. UncommentRegion

5. TabifyRegion

6. UntabifyRegion

7. ToggleTabs

8. NewIndentWidth

9. FormatParagraph

10. StripTrailingWhitespace

Run(Editorwindow)

1. PythonShell

2. CheckModule

3. RunModule

ShellMenu(Shellwindow)ViewLastRestart

RestartShell

InterruptExecution

Debug(Shellwindow)

1. GotoFile/Lie

2. Debugger

3. StackViewer

4. Auto-OpenStackViewer

Options(EditorandShellwindows)

1. ConfigureIDLE

2. CodeContext(availableonlyinEditor)

Windows

1. ZoomHeight

Help

1. AboutIDLE

2. IDLEHelp

3. PythonDocs

4. TurtleDemo

OtherThingsYouCanUseYoucanwriteyourcodesinotherIDEsortexteditorsotherthanIDLE,dependingonyourneeds.Thereisnorealguidelineinchoosingwhereyoushouldtypeoutandsaveyourcodes–aslongastheeditorthatyouareusinghelpsyoucodecomfortablyandcomeswithsyntaxhighlightingwhichwillhelpyouvisualizeyourcode,thenyouwillbeabletoachieveyourhackinggoalsandcreatethecodethatyouwanttouseinthefuture.

Hereareothereditorsandtheirfeaturesthatyoumightwanttocheckout:

PyCharmEducationalEdition

IfyouwanttofocusonlearningPythoninsteadofconcentratingonhowyoushouldbenavigatingyourwindows,thenthisistheeditorforyou.Youcanpullupexistingcodesintheeditortolearnhowcertainprogramsarewritten,orlearnusingthetutorialthatcomeswithit.

Youcandownloadthisfreeeditorfromwww.jetbrains.com.

SublimeText

SublimeTextallowsyoutouseapackagemanager,whichessentiallyworksforanypersonthatisusedtotypinginwordprocessors.Italsocomeswithfeaturessuchascodefolding,whichhideslinesofcodesthatyouarenotworkingon.

Takenotethatthisisnotafreesoftware,butitdoescomewithatrialperiodthatdoesnothaveatimelimit.

VIM

Thisfreesoftwarewillallowyoutodolotsofcustomizing,whichisgreatifyouareanexperiencedprogrammerthatwantstoworkusingsettingsthatyouaremostcomfortablewith.Anotherplusfactortothissoftwareisthatithasanextendedhistoryofusage,whichmeansthatyouhaveacommunityofusersthatyoucaneasilytapwhenyouneedsomehelp.

Ifyouarenewtoprogramming,thismightfeellikeadauntingtexteditortouse,butthesteeplearningcurvewillpayoffintheend.Bylearninghowtocodethroughhackingrightaway,youwillbeabletogetagoodgraspofPythonasyouexperienceitusingdifferenttoolsthatwerealreadymadebyotherhackers.

Coda

Thissoftwarecomeswithafreetrialforaweekandthenwillcost$99afterwards.Coda

isnotatexteditorthatisdevoidofbellsandwhistles–itcomeswithfeatureslikeSSHconnectivity,codecontrolstoconnectautomaticallytoahub,andaTerminalinterface.Ifyouaregunningtodevelopawebappforyourhacks,thenthisisprobablytheIDEthatwillworkbestforyou.

Nowthatyouhaveyourdevelopmentenvironmentsetup,it’stimeforyoutostartlearningaboutPython’sbasicconcepts.

Chapter2:PythonBasicsYourgoal,ofcourse,istomakePythongobeyondprintingatext.Todothat,youwillneedtolearnotherconceptsthatareessentialinaPythonscript.Youwillalsowanttocreateascriptthatiseasyforyoutounderstandandreviewinthefuture,justinanycaseyouwanttoimproveitandturnitintoaworkingtoolforyourhacks.

Inordertotakeinputsandmanipulatetheminordertogetcertainresults,youwillfirstneedtolearnhowvariablesandconstantsworkinthisprogramminglanguage.

CommentsThesearestatementsthatcomeafterthe#symbol.Thesepiecesoftextsallowyouto:

Explaintheproblemsthatyouareaimingtoovercomeorsolveinyourprogram

Takenoteoftheimportantassumptions,details,anddecisionsthatyouwanttoperforminthecode

Makingnotesinyourcodedoesnotonlyremindyouwhatyouwanttoachieveinyourcode,butalsohelpreadersthatwillbeusingyourprogramunderstandwhatlinesofcodearesupposedtodo.

LiteralConstantsLiteralconstantsarenamedassuchbecauseyoutakethesepiecesoftextfortheirliteralvalue.Theseconstantscanbe:

Numbers

Theycanbeintegers(plainwholenumbers)orfloats(numbersthathavedecimalpoints)

Strings

Thesearesequencesofcharacters,whichyoucanspecifyusingsinglequote,doublequotes,ortriplequotes.TakenotethatsingleanddoublequotesfunctionsimilarlyinPython,andthatyoucanexpressthemfreelyinsidetriplequotes.Hereisanexample:

Stringsarealsoimmutable,whichmeansthatyoucannotchangeastringonceyouhavecreatedit.

HowtoFormatStringsThereareinstancesinwhichyouwillwanttoconstructstringsfromadifferentpieceofinformation.Todothis,youwillneedtousethe method.Takealookatthisexample:

Onceyouaredone,savethispieceofcodeasstr_format.py.Thisishowit’sgoingtolooklikewhenyouruntheprogram:

Theformatmethodallowsyoutouseanargumentvaluetotaketheplaceofaparticularspecification.Takealookatthisexample:

Thispieceofcodewillgiveyouthisresult:

VariablesBecausetherewillbemultipleinstancewhereinyouwillneedtostoreinformationinyourcodeandthenmanipulatethem,youwillneedtohavesomevariables.Justlikewhatthenamemeans,variableshavevaryingvalues,suchasrealnumbers,strings,Booleans,dictionaries,orlists,whichyoucanaccessthroughcertainmethods.Takealookatthissamplecode:

Inthisexample,youareabletodefinethevariablenamedport,whichisgoingtobeusedtostoretheinteger21,andthevariablenamedbanner,whichisgoingtoholdastring.Inordertocombinethesevariablestogetherasasinglestring,youwillneedtousethevariableportthroughtheuseofthestr()function.

Sinceyouneedtoquicklyaccessthedatayoustored,youneedtoassignnamestovariables.Thisiswhereidentifierscometoplay.Identifiersworklikecodenamesthatyouusetopointouttosomethingthatyouhaveusedinyourcodeorprogram.Herearesomerulesthatyouneedtofollowwhenassigningthem:

Theinitialcharactershouldbealetterofthealphabetoranunderscore.

Theremainingcharactersshouldconsistofunderscores,letters,ordigits

Theyarecase-sensitive,whichmeansthatmycodeandmyCodedonotcalloutthesamevalueandnotinterchangeablewhenyouassignthemasanidentifier.

ObjectsThingsthatarereferredtoasanythinginthecodethatexistsinPythonarecalledobjects.IfyouaremigratingtoPythonfromanotherprogramminglanguage,youneedtotakenotethateverythinginPython,includingstring,numbers,andfunctions,isclassifiedasanobject.

ListsPythonallowsyoutomakeuseofalistdatastructurewhichisextremelyusefulwhenitcomestostoringcollectionsofobjects.Asaprogrammer,youcancreateliststhatcontaindifferenttypesofdata.Atthesametime,youcanalsomakeuseofseveralbuilt-intechniquesinPythonthatwillallowyoutoinsert,index,count,sort,append,remove,pop,andevenreverseitemsinalist.Takealookatthisexample:

Usingtheabovecode,youwereabletocreatealistthroughthemethodappend(),printallthespecifieditems,andthenmanagetosorttheitemsbeforeyouaskedtheprogramtoprintthemagain.Youwerealsoabletofindanitem’sindexandalsoremoveparticularitems.

DictionariesPython’sdictionarystructureallowsyoutomakeuseofahashtablethatcanbeusedtostorevirtuallyanyamountofobjects.Theprogram’sdictionarycontainsapairofitemswhichconsistsofakeyanditscorrespondingvalue.

Dictionariesareextremelyhelpfulincreatinghackingscripts.Forexample,youcancreateascannerthatisdesignedtoexploitvulnerabilitiesofaparticularsystem,suchasopenTCPports.Ifyouhaveadictionarythatwilldisplayservicenamesforcorrespondingportsthatyouwanttoexploit.Forexample,youcancreateadictionarythatwillallowyoutolookuptheftpkey,andthenprovideyouanoutputof21,whichcorrespondstoaportthatyoumaywanttotest.Youcanalsousedictionariestoperformbruteforceattackstocrackanencryptedpassword.WhatmakesPythonevenbetteristhatyoucancodeyourowndictionariesandusetheminotherscriptsthatyoumaywanttodevelopinthefuture.

Whenyoucreateadictionary,keysshouldbeseparatedfromtheircorrespondingvaluewithacolon,andtheitemsshouldbeseparatedusingcommas.Inthefollowingexample,youwillbeabletousethe.keys()methodtogiveyoualistofalltheavailablekeysinthedictionary,andthe.items()methodthatwillprovideyoualltheitemsthatthedictionarycontains.Takealookatthisexample:

NowthatyouknowthebasicconceptsthatmakePythonscriptsperformtasks,youarenowreadytostartusingtheminyourownscript.Inthenextchapter,youwilllearnhowareadablePythonscriptshouldlooklike.

Chapter3:WritingPythonProgramsNowthatyouareawareofsomebasicconceptsthatyouneedtograspinPython,it’stimetolearnsomeguidelinesthatyouneedtorememberwhenitcomestowritingaPythonprogram.Inthischapter,youwilllearnhowtousesomeofthemostbasicconceptstorunsimplecommandsandformatyourPythoncodesinsuchawaythatitwillbeeasierforyoutounderstandanddocumentthemlater.

HowtoUseLiteralConstantsandVariables

Pullupyourtexteditorandrunthefollowing:

Youroutputshouldlooklikethis:

Whathappenedinthisprogramisthatyouassignedaliteralvalueof5tothegivenvariableithroughanassignmentoperator,whichisthe=sign.Thatentirelineisconsideredastatementbecauseitindicatedthatsomethingshouldbedone,whichisconnectingthesaidvariabletoanumericalvalue.Afterwards,youprintedoutthevalueofibyusingtheprintcommand.

Afterwards,youadded1tothegivenvaluethatyoustoredinthevariablei,andthenyousavedit.Whenyouusetheprintstatementagain,yougetthevalueof6.

Atthesametime,youalsoassignedaliteralstringtothevariablesandthenproceededtousetheprintstatement.

PhysicalandLogicalLinesWhatyouseewhenyoutypeoutaprogramiscalledaphysicalline.WhatPythongetswhenyoutypeastatementiscalledthelogicalline.Withthissaid,thisprogramminglanguageassumesthateveryphysicallinethatyouseecorrespondstoagivenlogicalline.

Whileyoucanusemorethanonelogicallineonaphysicallinebyusingthesemicolon(;)symbol,Pythonencouragesthatprogrammerslikeyouinputasinglestatementinordertomakeyourcodesmorereadable.Thisway,youwillbeabletoseelinesthatyouareworkingonandavoidpossibleconfusionwhenyouareworkingontwodifferentlogicallinesandgetlostonwhatyouaresupposedtoworkon.

IndentationPythonisoneoftheprogramminglanguagesouttherewherewhitespace,especiallythespaceatthebeginningofeachlineofcodeisimportant.Byusingindentation,youcangrouptogetherblocks,orstatementsthatbelongtogether.Asaruleofthumb,seetoitthatyouareusingthesameindentationwhenyouareworkingonsimilarstatements.Alsorememberthatusingthewrongindentationcanmakeyourcodepronetoerror.Takealookatthisexample:

Whenyourunthiscode,youwillgetthisresult:

Pythonrecommendthatyouusefourspacesforyourindentations.Typicalgoodtexteditorswilldothisforyou.Aslongasyouareconsistentwiththespacesthatyouareusing,youwillbeabletoavoidunexpectedresultsinyourcode.

Nowthatyouknowthebasics,youcannowstartlearningthemoreinterestingstuff!

Chapter5:OperatorsandExpressionsMostofthestatements(alsocalledlogicallines)thatyouwillbewritinginyourcodewillincludeexpressions.Expressionsaredividedintooperandsandoperators.

Operatorsareessentiallyfunctionsthatdosomethinginyourcode,whicharerepresentedbysymbolsorkeywords.Theyusuallyrequirepiecesoninformationthattheycanworkon,whicharecalledoperands.Forexample,ifyouhavetheexpression4+5,theplus(+)signistheoperator,andthenumbers4and5areoperands.

PythonOperatorsTakealookathowexpressionslooklikeinaninterpreterprompt:

Whenyouevaluateexpressionsinaninterpreterpromptandyouusedtherightsyntax,youwillbeabletoseetheresultthatyouareexpectingrightafterthelogicalline.Sinceyouwillbeproducingcodesforyourownhackingtools,youwillneedtomemorizehowoperatorsareusedinacode.

AlsotakenotethatPythonusestheoperatorsaccordingtoprecedence.Thatmeansthatwhenyouaskyourcodetoperformcertainoperationsthathavehigherprecedence.Forexample,Pythonwillalwaysperformoperationsthatrequireittodivideormultiplyvariablesoveroperationsthatrequireittoaddorsubtract.Iftwooperatorshavethesamevalueofprecedence,thenPythonwillevaluatethemfromlefttoright.

HereisalistoftheoperatorsthatareavailableinPython.

Plus(+)

Addstwoobjects.

Forexample:

4+5willgiveyou9,and‘e’+‘j’givesyou‘ab’

Minus(-)

Subtractsonenumberfromanothernumber.Incasethatthefirstoperandintheequationisabsent,Pythonassumesthatitiszero.

Forexample:

-87willgiveyouanegativenumber,and80–40givesyou40.

Multiply(8)

Multipliestonumbersorrepeatsastringacertainnumberoftimes.

Forexample:

2*5givesyou10,and‘ha’*3willgiveyou‘hahaha’

Power(**)

Raisesacertainnumbertothepowerofthenextoperand.

Forexample:

3**3willgiveyou9(thisiscomputedas3*3*3)

Divide(/)

Dividesthefirstoperandwiththenextone.

Forexample:

4/2gives2

Divideandfloor(//)

Dividesthefirstoperandwiththenextone,andthenroundstheresulttothenearestnumber.

Forexample:

5//2givesyou2

Modulo(%)

Givesyoutheremainderofadivision

Forexample:

13%3willgiveyou1

Lessthan(<)

Givesyouaresultofwhetherthefirstoperandislessthanthenextone.ThecomparisonoperatorwillsaywhetheritisTRUEorFALSE.

Forexample:

3<9returnsgivesyouTRUE

Greaterthan(>)

Givesyouaresultofwhetherthefirstoperandisgreaterthanthenextone.TheoperatorwillalsosaywhetheritisTRUEorFALSE.

Forexample:

9>3givesyouTRUE

Lessthanorequalto(<=)

Givesyouaresultofwhetherthefirstoperandislessthanorequaltothenextone.

Forexample:

x=6;y=9;x<=ygivesyouTRUE

Greaterthanorequalto(>=)

Givesyouaresultofwhetherthefirstoperandisgreaterthanorequalthenextone

Forexample:

x=6;y=3;x>=ygivesyouTRUE

Equalto(==)

Tellsyouiftooperandsareequal.

Forexample:

x=3;y=3;x==ygivesyouTRUE

Notequalto(!=)

Tellsyouiftheoperandsarenotequal

Forexample:

x=3;y=4;x!=ygivesyouTRUE

ExpressionsExpressionsarecombinationsofoperatorsandvaluesinyourcode.Youcanthinkofitasanythingthat“expresses”somethingthathasavalue.Forexample,ifyouusethefunctioneval(1+1),youwillgetaresultthatprovidesyouthevalueofthesetwonumbersaddedtogether.

Takealookatthisexample:

Savethisasexpression.pyandthenrunitattheinterpreterprompt.Youshouldbeabletogetthisoutput:

Asyoumayhavenoticed,Pythonstoredvaluesinthevariables‘length’and‘breadth’,andyouareabletocalculatetheperimeterandtheareaofarectangleusingtheseexpressions.Youarealsoabletostorethevalueoftheexpressionlength*breadthinanothervariable,whichisnamedarea,andthendisplayeditusingtheprintfunction.

Nowthatyouareawareofhowyoucanusethebuildingblocksofaprogramminglanguage,youcannowreadytolearnhowyoucanusetheminacode!

Chapter6:FunctionsandModulesWritingacodeforhackingcanbetediouswhenyouarelimitedtousingoperations–justimaginehavingtowriteanoperationandthenrepeatthatoverandoveragainthroughoutyourscriptinorderforyourcodetodosomething.ItisagoodthingthatPythonallowsyoutomakeuseoffunctionsandmodulesthatwillallowyoutorepeatcertainactionswithinyourcodeandinotherscriptsthatyouwillbebuildinginthefuture.

Inthischapter,youwilllearnhowtocreateandmakeuseoffunctionsandmodules.Youwillalsolearnhowtoiteratecommandsthatyouhaveissuedinyourscriptinordertorepeatcertainactionsfordifferentelements,andhandleerrorsthatyoumayencounterinyourscript.

FunctionsInPython,afunctionallowsyoutocreateablockofcodethatwillbeabletodoanaction.Theyarealsoreusable,whichmeansthatyoucanprovideanametothatstatementblockandthenrunthisblockusingthenamethatyouassigneditanywhereintheprogramthatyouarebuildingwithoutanylimit.InPythonterms,thisiscalled“callingthefunction”.

Functionsareprobablythemostimportantcomponentofaprogramminglanguage.InPython,theyareusuallydefinedusingthekeyworddef,followedbyanidentifiernameforthefunctionthatyouwanttouse.Takealookatthisexample:

Savethisasfunction1.py,andthenrunitattheinterpreterprompt.Youshouldseethisoutputafterdoingso:

Whathappenedhereisthatyouareabletodefinethefunctionsay_hello,whichhasnoparameters,whichisthereasonwhythereisnovaluestatedinsidetheparentheses.Parametersareindicatedinfunctionsinordertoincludeaninputthatyoucanusetopassdifferentvaluestothefunctionandgetaspecificresultthatyouhaveinmind.

Alsonoticethatyouhavemanagedtocallthefunctiontwotimesinthisexercise,whichmeansthatyoudidnothavetowritetheentirecodeagainforPythontorepeataparticularaction.

FunctionParametersFunctionsareabletotakeinvaluesthattheywillbeabletouse,whicharecalledparameters.Parametersactsimilarlytovariables,exceptthatyouaredefiningtheirvalueswheneveryoucallthefunctionandthatyouhavealreadyassignedvaluestothemonceyourunthefunction.

Parametersarespecifiedwithinapairofparentheseswhenyouaredefiningthefunctionandareseparatedusingcommas.Ifyouneedtocallthefunctioninyourcode,youwillneedtosupplythevaluesinthesameway.Alsotakenotethatwhenyouaresupplyingvaluetoyourfunctionwhileyouarenamingit,thesevaluesarecalledparameters;butwhenyouaresupplyingvaluesasyoucallthefunction,thesevaluesarecalledarguments.Takealookatthisexample:

Savethisasfunction_param.pyandthenrunitattheinterpreterprompt.Youshouldgetthisoutput:

KeywordArgumentsTherewillbeinstancesasyoucodewhereinyouhavetoomanyparametersinyourfunction–ifyouwanttospecifysomeofthem,thenyoucanusekeywordargumentsinordertogivevaluesforsomeoftheparameters.Doingsowillgiveyoutheadvantageofeasilyusingthefunctionwithouthavingtoworryaboutthearguments’order,andthatyoucanassignvaluestotheparametersthatyouwanttouse,especiallywhentheotherparametersthatareavailablealreadycontainsargumentvaluesthataresetindefault.

Takealookatthissamplecode:

Savethiscodeasfunction_keyword.py,andthenrunitattheinterpreterprompt.Youshouldgetthefollowingoutput:

ThereturnStatementIfyouwanttobreakoutofthefunction,orifyouwanttoreturnavaluefromthefunction,thenthisstatementwillprovetobehelpful.Takealookatthisexample:

Savethiscodeasfunction_return.pyandthenrunitattheinterpreterprompt.Youshouldgetthefollowingoutput:

DocStringsPythoncomeswithacoolfeaturecalleddocstrings,whichisatoolthatyoucanusetodocumentthecodethatyouarecreatingandmakeiteasiertounderstand.Youcanalsogetadocstringfromafunctionwhilethecodeisalreadyrunning.Takealookatthisexample:

Savethiscodeasfunction_docstring.pyandthenrunitontheinterpreterprompt.Youshouldgetthefollowingoutput:

Whathappenedhereisthatyouareabletoviewthedocstringforthefunctionthatyouhaveused,whichisthefirststringontheinitiallogicalline.Takenotethatdocstringscanalsobeusedinclassesandmodules.

IterationTherearesomeinstanceswhereinyoumayfindittoredundanttowritethesamecodemultipletimestodoasimilarfunction,suchascheckingdifferentIPaddressesoranalyzedifferentports.Forthisreason,youmaywanttouseafor-loopinsteadtoiteratethesamecodefordifferentelements.Forexample,ifyouwishtoiterateacodeforthesubnetofIPaddressesfrom192.168.0.1through192.168.0.254,youcanuseafor-loopthatcontainsarangeof1to255todisplaytheentiresubnet.Takealookatthissamplecodetoseehowitisdone:

Ifyouwanttoiteratethesamecodethroughalistofknownportstoanalyzeasystem’svulnerabilities,youcaniteratethroughalistofelementsthatyouwanttocheckinstead.Takealookatthisexample:

ExceptionHandlingEvenifyouarealreadyabletowriteaprogramwithcorrectsyntax,youmaystillgothroughsomeerrorsuponexecutionorruntime.Forexample,whenyoudivideanythingbyzero,youarelikelytoexperiencearuntimeerrorbecausePythonknowsthatitisimpossibletodoso.Whenyouattempttoperformthisaction,Pythonmightreturnwiththisoutput:

Ifyouwanttofixtheerrorwhileyouarealreadyrunningyourcode,Python’sabilitytoperformexceptionhandlingwillcomeinhandy.Usingtheexampleabove,youcanusethetryorexceptstatementinordertomakeuseoftheexceptionhandlingsothatwhentheerrorhappens,theexceptionhandlingfeaturewillcatchtheerrorandthenprintthemessageonthescreen.Takealookatthisexample:

Ifyouwanttoseewheretheerrorspecificallyhappenedinyourscript,youcanusethefollowingcodeinstead:

ModulesIfyouwanttomakeuseofthefunctionsthatyouhavealreadycreatedfromanotherprogramtoanother,insteadofhavingtorewritetheentirecode,thenyoucanuseofmodules.

Thesimplestwaytomakemodulesistocreateafilethatcontainsallthevariablesandfunctionsthatyoumayneedtouseinafutureprogramandthensaveitasa.pyfile.Alternatively,youcanalsocreateyourmodulesinalanguageinwhichthePythoninterpreteriswritten,suchastheClanguage.Youcanalsohaveamoduleimportedbyanotherprogramanduseallthefunctionalitysavedinthere,whichisthesameasyouusethestandardlibrariesthatyouuseinPython.

Takealookathowyoucanuseastandardlibrarymodulethroughthisexample:

Savethiscodeasmodule_using_sys.pyanthenrunitontheinterpreterprompt.Youshouldgetthisoutput:

Whathappenedhereisthatyoufirstimportedthesysmodule.Byusingtheimportstatement,youareabletotellpythonthatyouwanttouseamodulethatcontainsthefunctionalitythatisrelatedtothePythonenvironment.Whenthisprogramminglanguageexecutesthestatement,itwillthenlookforthe.sysmodule.Sincethisisabuilt-inmodule,Pythonknowsthelocationwhereitcanbefound.

InanycaseyouaretryingtoimportamodulewritteninPython,theinterpreterwillthensearchalldirectoriesthatarelistedinthevariablesys.path.Onceitisfound,thestatementsfoundinthatmodulewillberun,makingitavailableforyoutouse.Thisinitializationprocessonlytakesplacethefirsttimeyouimportamodule.

SysModulePythonhasabuilt-inmodulethatprovidesyouaccesstoallobjectsthattheprogramminglanguage’sinterpretermaintainsoruses.Calledthesysmodule,thismoduleincludescommandlinearguments,maximumsizeofintegersthatcanbeused,flags,pathhooks,aswellasotheravailablemodules.

Beingabletointeractwiththesysmodulewillallowyoutocreatedifferentscriptsthatyoucanusefordifferenthackingpurposes.Forexample,youmaywanttoanalyzedifferentcommandlineargumentsduringruntime.Ifyouaregoingtobuildascannertodiscoversystemvulnerabilities,youmaywanttopassafilenameasacommandlineargument,whichcanbedonebyusingthelistsys.argvwhichiscomprisedofallthecommandlinearguments.Takealookatthissamplecodetoseehowthismoduleisused:

Whenyourunthispieceofcode,youwillseethatthecommandlineargumenthasbeenanalyzedandthenPythonprintsouttheresultsonthescreen.Theoutputwilllooklikethis:

OSModulePython’sOSmoduleprovidesagreatdealofroutinesfordifferentoperatingsystems,suchasMac,Posix,andNT.Usingthismodule,youcanallowtheprogramminglanguagetointeractonitsownwiththefile-system,permissions,userdatabase,anddifferentOSenvironment.

Usingthepreviousexample,you,theuser,submittedatextfileasacommandlineargument.However,itwillalsobeofvalueifyoucancheckifthefilethatyouhavepassedexistsandthecurrentuserofthemachineyouaretargetinghavethenecessarypermissionstoreadthatfile.Todeterminethis,youcancreateacodethatwilldisplayanerrormessageifeitheroneoftheconditionisnotmet.Youcanusethiscodetodothat:

Tocheckyourcode,youcanattempttoreadafilethatisnotavailableinthesystem,whichwillcausethescriptyoujusttypedintodisplaytheerror.Afterwards,youcanenterafilenamethatwillbesuccessfullyread.Finally,youcancreatepermissionrestrictionsandseethatthescriptthatyouhavecreatedprintoutaconventionalAccessDeniedmessage:

ThePythonStandardLibraryPython’libraryisprettymuchthecollectionofalmosteveryelementthereisinthisprogramminglanguage.Thisextensivecollectioncontainsseveralbuilt-inmodulesthatallowyoutoaccessdifferentfunctionalitiesinthesystem.ThePythonsstandardlibraryisalsoresponsibleforprovidingyouaccesstomodules,whicharedesignedtoenhancePython’sinherentportability.Thismeansthatyouareabletodealawaywithplatformswhenitcomestocreatingyourcodes.

IfyouarerunningPythonfromaWindowsmachine,youarelikelytohavetheentirestandardlibraryincludedinyourinstallation.IfyouareoperatingusingUNIXoranysimilaroperatingsystem,youmayneedtousethepackagingtoolsavailableinyouroperatingsystemifyouwanttogetsomeoftheoptionalcomponents.

Atthispoint,youalreadyknowtheessentialsinPython.Asyoucreateyourowncodesforhackingorimportmodulesfromlibraries,youwillbeabletodiscovermorefunctionalitiesandlearnwhattheyarefor.

Sinceyouarelearninghowtocodeinordertohack,thebestwayforyoutopickupyourpaceistolearnasyoucreatetoolsthatyoucanuseforhacking.Thismeansthatitistimeforyoutodotheexcitingstuff!

Chapter7:SettingUpforHackingAtthispoint,youhaveabasicideaofhowPythonworksandhowprogramswerecreatedusingthis programming language. Now, you are ready to learn how you can use Python scripts tocompromisewebsites,networks,andmore.

Learninghow tohackentailsbeingable to setup the rightenvironment thatyoucanwork in inorder todevelopyourownexploitation tools.Sinceyouhavealready installedPythonand thestandard library thatcomeswith it,youareprettymuchsetup forhacking.Allyouneed todonowistoinstallothertoolsandlibrariesthatyoucanusefortheexploitsthatwillbedetailedinthisbook.

InstallingThirdPartyLibrariesThirdpartylibrariesareessentiallylibrariesthatdonotcomenativewithyourinstallationofPython.Allyouneedtodotogetthemistodownloadthemfromatargetedsource,performuncompressingonthepackagethatyoujustdownloaded,andthenchangeintothetargetdirectory.

Asyoumighthavealreadyguessed,thirdpartylibrariesareextremelyusefulwhenitcomestodevelopingyourowntoolsoutoftheresourcesthatarealreadycreatedbysomeoneelse.SincePythonisahighlycollaborativeprogramminglanguage,youcanuselibrariesthatyoumayfindfromwebsitesourcessuchasGitHuborthePythonwebsiteandincorporatethemintoyourcode.There

Onceyouareinsidethedirectory,youcaninstallthedownloadedpackageusingthecommandpythonsetup.pyinstall.Takealookatthisexampletoseehowitisdone:

Whatjusthappenedhereisthatyouwereabletoinstallapackagethatwillallowyoutoparse

nmapresultsbydownloadingthepython-nmappackage.

Tip:Ifyouwanttoestablishyourdevelopmentenvironmentfaster,youmaywanttogetacopyoftheBackTrackLinuxPenetrationDistribuion,whichessentiallyallowsyoutogetaccesstotoolsthatareusedforforensics,networkanalysis,penetrationtesting,andwirelessattacks.

YourFirstPythonProgram:APasswordCrackerPython’sstrengthliesintherobustlibrariesthatyoucanusewhencreatingyourownprograms.ThisPythonprogramwillnotonlyteachyouhowyoucancrackpasswords,butalsohelpyoulearnhowtoembedalibraryinyourcodeandgetresultsthatyouwant.

Towritethispasswordcracker,youwillneedtohaveacrypt()algorithmthatwillallowyoutohashpasswordsthatareintheUNIXformat.WhenyoulaunchthePythoninterpreter,youwillactuallyseethatthecryptlibrarythatyouneedforthiscodeisalreadyrightinthestandardlibrary.Now,tocomputeforanencryptedhashofaUNIXpassword,allyouneedtodoistocallthefunctioncrypt.crypt()andthensetpasswordandsaltasparameters.Thecodeshouldreturnwithastringthatcontainsthehashedpassword.

Hereishowitshouldbedone:

Now,youcantryhashingatarget’spasswordwiththefunctioncrypt().Onceyouareabletoimportthenecessarylibrary,youcannowsendtheparameterssalt“HX”andthepassword“egg”tothefunction.Whenyourunthecode,youwillgetahashedpasswordthatcontainsthestring“HX9LLTdc/jiDE”.Thisishowtheoutputshouldlooklike:

Whenthathappens,youcansimplywriteaprogramthatusesiterationthroughoutanentiredictionary,whichwilltryagainsteachwordthatwillbepossiblyyieldthewordusedforthepassword.

Now,youwillneedtocreatetwofunctionsthatyoucanuseintheprogramthatyouaregoingtowrite,whicharetestPassandmain.Themainfunctionwillpullupthefilethatcontainstheencryptedpassword,whichispassword.txt,andwillthenreadallthecontentsinthelinesthatthepasswordfilecontains.Afterwards,itwillthensplitthelinesintothehashedpasswordandits

correspondingusername.Afterthat,themainfunctionwillcallthetestPassfunctiontotestthehashedpasswordsagainstthedictionary.

ThetestPassfunctionwilltakethepasswordthatisstillencryptedasaparameterandthenwillreturnafterexhaustingthewordsavailableinthedictionaryorwhenithassuccessfullydecryptedthepassword.Thisishowtheprogramwilllooklike:

Whenyourunthiscode,youwillbeabletoseethisoutput:

Judgingfromtheseresults,youwillbeabletodeducethatthepasswordfortheusername‘victim’isrightinthedictionarythatyouhaveavailable.However,thepasswordfortheusername‘root’isawordthatyourdictionarydoesnotcontain.Thismeansthattheadministrator’spasswordinthesystemthatyouaretryingtoexploitismoresophisticated,butcanpossiblybecontainedinanotherdictionarytype.

Atthispoint,youarenowabletosetupanidealhackingenvironmentforPythonandlearnhowtomakeuseofavailableresourcesfromotherhackers.Nowthatyouareabletocreateyourfirsthackingtool,it’stimeforyoutodiscoverhowyoucanmakeyourownhackingscripts!

Chapter8:NetworkHacking

Anetworkattackisanyprocessortacticthatwillallowahackertocompromiseanetwork’ssecurity.Whenyouareabletoperformanetworkattack,youcanuseauser’saccountandtheprivilegesthatareattachedtoit,stealormodifystoreddata,runacodetocorruptasystemordata,orpreventanauthorizeduserfromaccessingaservice.

Inthischapter,youwilllearnhowtoattackanetworkusingsomethird-partytoolsandcodesthatyoucanwriteusingPython.Atthesametime,youwillalsogainbetterawarenessonhowhackersgaininformationabouttheirtargetandperformattacksbasedonthevulnerabilitiesthattheywereabletodiscover.

Reconaissance:TheOpeningSalvotoYourAttackHackingasystembeginswithreconnaissance,whichisthediscoveryofstrategicvulnerabilitiesinnetworkbeforelaunchinganycyber-attack.Youcanthinkofthisasahacker’sresearchabouttheirtargets–themoreinformationtheyknowaboutthenetworkthattheywanttohack,themoreideastheycangatheraboutthebesttoolsthattheycanuseinordertolaunchattacksthataremostlikelytobecomeundetectedbythetargeteduserwhilecausingthemostdamagepossible.

Takenotethateveryonecanbeahacker’starget,whichmeansthatlearninghowhackersperformreconnaissancemeansbeingabletoprotectyourownsystemaswell.Wheneveryouconnecttotheinternetandsenddataovertheweb,youareleavingbehindfootprintsthathackerscantracebacktoyou.Whenthathappens,itispossiblethathackerswillwanttostudyyouractivitiesoveryour network and discover vulnerabilities in your system that willmake it easier for them toinfiltrateandstealdatathatcanbeofvaluetothem.

Inthissection,youwilllearnhowtobuildsimplescriptsthatwillallowyoutoscanyourtarget’svulnerableTCPports.Inordertointeractwiththisopenports,youwillalsoneedtocreateTCPsockets.

PythonisoneofthemodernprogramminglanguagesthatallowsyoutogainaccesstoBSDsocketinterfaces.Ifyouarenewtothisconcept,BSDsocketsgiveyouaninterfacethatwillallowyoutowriteapplicationssothatyoucandocommunicationswithanetworkrightinbetweenhosts.BydoingaseriesofsocketAPIutilities,youwillbeabletoconnect,listen,create,bind,orsendtrafficonatarget’sTCP/IPsockets.

Whathappenswhenyouareabletoexploitatarget’sTCP?IfyouareabletoknowtheIPaddressandtheTCPportsthatareassociatedwiththeservicethatyouwanttotarget,thenyoucanbetterplanyour attack.Most of the time, this information is available to systemadministrators in anorganizationand thisdata isalsosomething thatadminsneed tohide fromanyattacker.Beforeyoucanlaunchanyattackonanynetwork,youwillneedtogainthisinformationfirst.

MakingYourPortScanner

Portscanningisamethodinwhichyoucanassesswhichoftheportsinatargetedcomputerisopen,andwhatkindofserviceisrunningonthatspecificport.Sincecomputersareoperatingtocommunicatewithotherdevicesandperformafunctionbyopeningaporttosendandreceivedata,openportscanbeavulnerabilitythathackerswillwanttoexploit.Thinkofanopenporttobesimilartoanopenwindowtoaburglar–theseopenportsserveasafreepassagetoanyhackerthatwillwanttostealdataorsetupshopinsideacomputertoexploititsweaknessesforanextendedamountoftime.

Takenotethatportscanningisnotanillegalactivitytodo–infact,networksecuritypersonnelscantheportsofclientcomputersinordertolearnabouttheirvulnerabilitiesandapplythesecurityprotocolneeded.However,portscanningisalsothebestwayforanyhackertodiscovernewvictimsandfindoutthebestwaytohacktheirsystem.Atthesametime,repetitiveportscanscanalsocauseadenialofservice,whichmeansthatalegitimateusermaynotbeabletousea

particularnetworkingserviceduetotheportsexhaustingtheirresources.

Aportscannerwillallowyoutolookatthehostsandtheservicesthatareattachedtothem.TheyessentiallyThissectionwillenabletowriteyourownprogramforaTCPportscannerthatwillbeabletodoafullconnectscantothetarget’sTCPinordertoidentifythehoststhatyoumaywanttoexploitinthefutureusingthesocketbuilt-inmodule,whichinturngivesyouaccesstotheBSDsocketinterface.

Asyoumayhavealreadyguessed,socketsarebehindmostlyanythingthatinvolvesnetworkcommunications.Whenyoupullupawebbrowser,yourcomputeropensasocketinordertocommunicatetoawebserver.Thesamethinghappenswhenyoucommunicatetoothercomputersonline,orsendarequesttoyourprinteroveryourWi-Fi.

Takealookatsomeofthesocketfunctionsthatyouaregoingtouse:

Withthisinformation,youcancreateasimpleportscannerthatwillallowyoutoconnecttoeveryportthatyouareabletodefinethatcorrespondstoaparticularhost.Pullupyourtexteditorandthensavethefollowingcodeasportscanner.py:

Whenyourunthisprogramattheinterpreterprompt,thisishowtheoutputshouldlooklike:

UsingtheMechanizeLibrarytoPerformAnonymousReconnaissanceMostcomputerusersuseawebbrowsertonavigatewebsitesandviewcontentovertheInternet.Eachwebsitehasadifferentfeatures,butwillusuallyreadaparticulartextdocument,analyzeit,andthendisplayittoauser,justlikethewayasourcefileinteractswiththePythoninterpreter.

UsingPython,youcanbrowsetheinternetbygettingandparsingtheHTMLsourcecodeofawebsite.Therearedifferentlibrariesthatcomewiththisprogramminglanguagethatcanhandlewebcontent,butforthishack,youwillbeusingMechanize,whichincludestheprimaryclasscalledBrowser.Takealookatthissamplescriptthatwillshowyouhowtogetasourcecodeofawebsite:

Whenyourunthisscript,youwillseesyngress.com’sHTMLcodefortheirindexpage,whichwilllooklikethis:

EnsuringAnonymityWhileBrowsingNowthatyouknowhowtogetawebpage,youwillwanttocreateascriptthatwillallowyoutoanonymouslyretrieveinformationfromawebsite.Asyoumayalreadyknow,webserversseetoitthattheylogtheIPaddressesofdifferentusersthatviewtheirwebsitesinordertoidentifythem.ThiscanusuallybepreventedbyusingaVPN(virtualprivatenetwork),orbyusingTor.WhathappenswhenyouuseaVPNisthatalltrafficgetsroutedtotheprivatenetworkautomatically.Withthisconcept,yougettheideathatyoucanusePythontoconnecttotheproxyserversinstead,whichwillgiveyourprogramanaddedlayerofanonymity.

YoucanusetheBrowserclasstospecifyaproxyserverthatwillbeusedbyaparticularprogram.Forthisscript,youcanusetheHTTPproxyprovidedbywww.hidemyass.com.Justinanycasethisproxyisnotavailabletobeusedanymore,youcansimplygotothewebsiteandselectanHTTPproxythatyoucanuse.Youcanalsogetothergreatproxiesforyourcodesathttp://rmccurdy.com/scripts/proxy/good.txt.

Youwillthenseethatthewebsiteyouaretryingtoaccessbelievesthatyouareusingthe216.155.139.115IPaddress,whichisactuallytheIPaddressthatyourproxyprovidedyou.Now,continuebuildingyourscript:

Atthispoint,yourbrowseralreadycontainsasinglelayerofanonymity.However,websitesdouseastringcalleduser-agentinordertoidentifyuniqueusersthatlogintotheirsite.ThisstringwillusuallyallowthewebsitetogetusefulinformationaboutauserinordertoprovideatailoredHTMLcode,whichthenprovidesabetteruserexperience.However,maliciouswebsitescanalsousethatinformationtoexploitthebrowserthatisbeingusedbyatargeteduser.Forexample,therearecertainuser-agentstringsthatsometravelwebsitesusetodetectusersthatbrowseusingMacbooks,whichthenproceedtogivetheseusersmoreexpensiveoptions.

SinceyouareusingMechanize,youcanchangetheuser-agentstringjustlikehowyouchangetheproxy.Youcanmakeuseofavailableuser-agentstringsfromhttp://www.useragentstring.com/pages/useragentstring.phpthatyoucanuseforthenextfunctionthatyouaregoingtomake.Now,youwillbecreatingascriptthatwillallowyoutotestachangeonyouruser-agentstringtotheNetscapebrowser:

Whenyourunthiscode,youwillbeabletoseethatyouareabletobrowseawebpageusingafalseuser-agentstring.ThewebsitethatyouarebrowsingnowthinksthatyouareusingaNetscape6.01browserinsteadofsimplyusingPythontofetchthepage.

Whathappensafteristhatwebsitesthatyouaregoingtovisitwillattempttopresentcookiesthattheycanuseasauniqueidentifierinordertoidentifyyouasarepeatvisitorwhenyougobacktotheirsitethenexttime.Topreventthesewebsitesfromidentifyingyou,youwillneedtoseetoitthatyouclearallthecookiesfromyourbrowserwheneveryouperformfunctionsthatyouwanttobeanonymous.Anotherbuilt-inlibraryinPython,calledtheCookelib,willallowyoutomakeuseofvariouscontainertypesthatwillallowyoutodealwithcookiesthatwebsitepresentyou.Forthisscript,youwillbeusingacontainertypethatwillallowyoutosavecookiestodisk,andthenprintoutthecookiesthatyoureceivedduringyoursession:

Whenyourunthisscript,youwillseeyoursessionIDcookieforbrowsingtheSyngresssite:

FinalizeYourAnonymousBrowserintoaPythonClassAtthispoint,youhaveanideaofallthefunctionsthatyouwanttoincludeinyouranonymousbrowser,andthatinordertomaketheentireprocessofimportingallthesefunctionstoallfilesthatyouwillbecreatinginthefuture,youwillneedtoturnthatintoaclass.Thiswillallowyoutosimplycalltheclassusingabrowserobjectinthefuture.Thisscriptwillhelpyoudothis:

Thisclassnowcontainsuser-agentslist,aswillasproxyserverlistthatyoumaywanttousewhenyoubrowse.Italsocontainsthefunctionsthatyouwereabletocreateearlier,whichyoucancallindividuallyorallatonceusingtheanonymizefunction.Theanonymizefunctionwillalsoallowyoutoselecttheoptiontowaitfor60secondswhichwillincreasethetimeofrequeststhatyousend.Whilethiswillnotchangeanythingintheinformationthatyousubmittothewebsite,thisstepwilldecreasethechancethatthewebsitesthatyouarevisitingwillrecognizethattheinformationbeingsenttothemcomesfromasinglesource.YouwillalsonoticethatthefileanonBrowser.pyincludesthisclass,andshouldbesavedinalocaldirectorycontainingscriptsthatwillcallit.

Now,youcanwriteascriptwhereyoucanusetheclassthatyouhavejustcreated.Inthisexample,youwillbeenteringvotesforanonlinecompetitiononthewebsitekittenwar.comwhereyouhavetovoteforkittensbasedontheircuteness.Becausethevotesonthewebsitewillbetabulatedaccordingtoauser’ssession,youwillneedtohaveuniquevisitstothewebsitein

orderforyourvotestobecounted.Usingthisscript,youshouldbeabletovisitthetargetedwebsiteanonymouslyfivetimes,whichwillallowyoutoenterfivevotesusingthesamecomputer:

Afterrunningthisscript,youwillbeabletofetchthetargetedwebpageusingfivedifferentuniquesessions,whichmeansthatyouareusingdifferentcookieseverytimeyouvisit.

WirelessAttack:DnspwnAttackThisattackiscreatedbyusingtheairpwntool,whichisaframeworkforpacketinjectionforwireless802.11.Thistooliscreatedtolistentoincomingpacketsandtheninjectscontenttotheaccesspointwhentheincomingdatamatchesapatternthatisspecifiedintheconfigfile.Toyourtarget,yourairpwnlooksandbehavesliketheserverthatheistryingtocommunicateto.ThistoolwasfirstcreatedtotargetHTTP,butitcanalsobeusedtoexploitDNS.

Inanessence,usingadnspwnattackentailsluringyourtargettovisitamaliciouswebpagethatwillinstallmalwaretoyourtargetthroughdownload,ortospoofaparticularwebsitetostealyourtarget’scredential.Toperformthisattack,youwillneedtohaveBacktrackorKaliLinuxinstalledinyourcomputer,aswellasawirelesscardadapter.

Followthesesteps:

1. Setupyourwirelessmonitor

Inordertosniffyourtarget’swirelessactivity,youwillneedtosetupyourwirelesscardadaptertomonitormode.Todothis,pullupairmon-ngfromKaliLinuxandthenenterthefollowingcommand.

Now,youwillbeabletocapturedatarightinthedemo_insecure(target)network.

Onceyouhaveamonitorupandrunning,youcanstartcreatingthecodeforyourattack.

2. Createyourcode.

Youwillneedtomakeuseofthescapymoduleinordertoperformthednspwnattack.Todothis,youwillneedtosniffalltheUDPpacketsthatcomeswiththeport53destinationandthensendthepackettothesend_responsefunctionthatyouwillcreatelater.

Nowthatyouhavethescapymodule,wecannowmakethefunctionthatwillallowyoutoconstruetherequestfortheneededinformationandthendoresponseinjection.Youcandothisbyworkingupthefollowinglayers:

802.11Frame–switchthe“to-ds”to“from-ds”flag,whichwillmakeitseemliketherequeststhatyouaremakingarecomingfromtheaccesspoint

802.11Frame–changetheMacaddressesofthedestinationandsource

IPlayer–changetheIPaddressesofthedestinationandsource

UDPlayer–changetheportsofthedestinationandsource

DNSlayer–Putinthe“answer”flag,andthenaddtheanswerthatyouhavespoofed.

Thescapemodulemakestheentireprocesssimplebyremovingawayalotofdetailsthatyoudonotneedtobeconcernedabout.Oncetheotherdetailshasbeenabstractedawaybyscapy,youcanusethefollowingcode:

Atthispoint,youhavealltheflagssetforyourattack.ThenextstepistomakeandaddtheDNSanswer:

Finally,injecttheresponsethatyouhavespoofed:

KickaUserOutofYourNetwork

Thishackisasolutionthatyoumighthavebeendreamingof,especiallyifyouareusinganetworkthathasalotofotherusersinit.Asyoumayhavenoticed,thereisacertainlimitwhenitcomestosendingandreceivingdatathroughthenetworkandyourownnetworkinginterfaces.Thereasonforthislimitistheamountofbandwidththatyouhave,andifotherusersarenothoggingthebandwidth,thefasteryourconnectionswillbe.

Whenallthebandwidththatshouldbeavailabletoyou,youareexperiencingaDoS(DenialofService).YoucanactuallyforceaDoStoanotheruserbysearchingandmanipulatingaremotehost’sservice.Onceyoualreadyfoundthatservice,youcanmaketheprogrambehaveinawaythatitisnotsupposedtodo,whichwillcausetheremotehosttotakeupallitsavailableresourcesandthentakeitoffline.Alternatively,youcanalsocauseaUDPflood,whichisdonebysendingahugequantityofUDPpacketstoseveralportsonyourtarget’sremotehost.ThiswillcausethehosttoignoreanyapplicationthatarelisteningtothatparticularhostandthenreplywithapacketthatsaysICMPDestinationUnreachable.

Todothis,allyouneedtodoistopullupyourtexteditorandinputthefollowingcode:

Savethiscodeasudpflood.py,andthenselectallfileoptionsuponsaving.Torunthecode,pullupIDLEandthenexecutetheprogram,whichwillpromptyoutoenteralltheotherinformationthatyouneed.Takenotethatthishackisdirectedtoonlyoneport,butifyouwanttoexploitallother65,535portsthatareavailable.

Chapter9:HacksfortheWebYoumaybewonderinghowtogetpastcertainwebsiteprotectionpoliciesinordertogetafilethatyouwant,browseanonymously,orgetmoreinformationaboutthewebsitethatyouwanttopenetrate to launchamassiveattack.Inthischapter,youwill learnhowyoucanperformCreathacksonawebsiteusingsomeprogramsthatyoucancreateusingPython.

CreatinganSSHBotnetNow that you know how to create a port scanner and you are aware of how you can findvulnerable targets,youcannowproceed toexploit theirvulnerabilities.Oneof theways todothisistoexploittheSecureShellprotocol(SSH)inordertogetlogincredentialsfromclients.

What isabotnet?Bots,as thenameimplies,are incrediblyusefulwhenitcomestoautomatingservicesinpracticallyanydevice.Botnets,ontheotherhand,isagroupofbotsthatarejoinedtogetherbyanetworkwhichallowssystemadministratorsetoefficientlydoautomatedtasksoveranentiresystemofusersthatareconnectedtogetherbyaserveroralocalnetwork.Whilebotnetsareessentiallytoolsforeasymanagingofseveralcomputers,theycanalsobetoolsthatyoucanuseforunintendedpurposes,suchascreatingaDoSorDDoS(DistributedDenialofService)thatmaycauseawebsitetoloadmultipletimesinasessionorforcommentingonsocialmediasitescontinuously.

Here is aprogram thatwill allowyou tocreateyourownbotnetusinganotherpopularPythonlibrarycalledFabric,whichwillenableyoutocreateanapplicationcalledC&C(commandandcontrol)thatwillallowyoutomanagemultipleinfectedhostsoverasecureshellhost.

CreatingtheC&CAssumingthatyou,astheattacker,alreadymanagedtocompromisetheSSHandalreadyhaveaccesstothem.Assumingthatthehostscredentialsarestoredinafilethathasthisformat:username@hostname:portpassword.

Nowthatyouhavethesecredentials,youwillneedtoconsiderthefunctionsthatyouneedtocreate.Thismaymeanthatyouneedtorunastatuschecktoseerunninghosts,makeaninteractiveshellsessiontocommunicatewithatargetedhost,andperformacommandonselectedhosts.

Tobegin,youwillneedtoimporteverymemberofthenamespacefabric.api:

Afterthat,youwillneedtohavetheenvironmentvariables,env.passwords(mapsthehoststringsandthepasswordsthatyoucanuse)andenv.hosts(managesthehosts’masterlist),tobeabletomanageallthehoststhatyouwanttotarget.Onceyouhavethesesetup,youwillnothavetoentereachpasswordforeachnewconnection.

Nowthatyouhavethissetup,youcannowproceedtorunningthecommands.Herearethefunctionsthatyoucanusetocanuse:

local(command)–runsacommandonthetargetedlocalsystem

sudo(command)–performsashellcommandremotelyusingsuperuser(oradmin)privileges

put(local_path,remote_path)–uploadsfilesremotely

open_shell()–pullsupaninteractiveshellremotely

run(command)–performsashellcommandremotely

get(remote_path,local_path)–downloadsfilesremotely

Youcannowcreateafunctionthatwillallowyoutocreateacommandstring,andthenrunit.Here’sthecodetocreatetherun_command:

Now,youcancreateataskthatwillallowyoutomakeuseoftherun_commandfunction,whichwillenableyoutocheckwhichhostsareactivebyexecutingthecommandcalleduptime:

Toperformtheothertasks,youwillwanttocheckwhichhostsyouwouldwanttogivetheothercommandsortocreateashellsessionto.Tobeabletodothis,youwillneedtocreateamenuthatwillenableyouexecutetheothertaskswiththespecifiedhostsusingtheexecutefunctionofFabric.Hereishowthispartofthecodeshouldlooklike:

Savethecodeasfabfile.pyandthenrunitontheinterpreterprompt.Thisisswhattheentirecodelookswhenyourunit:

Youwillseethatyouwereabletogaincontrolofallthemachinesthatyouhaveaccessto.

ScrapingWebsitesthatNeedsLoginCredentialsIfyouwanttominedatafromawebsite,youwillfindthatyouwillfirstneedtologinbeforebeingabletoaccessanyinformationthatyouwant.Thismeansthatinordertogetthedatathatyouneed,youwillfirstneedtoextractallthedetailsthatyouneedtologintoyourtargetedwebsite.

StudyingtheTargetWebsiteHere’sthescenario:youwanttoscrapedatafromthebitbucketsite,whichyoucanaccessbyloggingintobitbucket.org/account/signin.Sinceitispromptingyoutosupplyusercredentials,youareunabletogointothewebsiteandminetheinformationthatyouwant.Asyoumayhaveguessed,youwillhavetobuildadictionarythatwillallowyoutoputindetailsforthelogin.

Inordertofindoutwhatyouneedtoinputthecredentialsthatyouneed,youwillneedtoinspecttheelementsofthefield“usernameoremail”.Youcandothisbyright-clickingonthefieldandthenselectingon“inspectelement”.

Dothesameforthepasswordfield:

Now,youareawarethatyoushouldbebeusing“username”and“password”askeysinyourdictionary,whichshouldgiveyouthecorrespondingcredentialsasvalue.

Next,searchforaninputtagthatishiddeninthepagesourcethatislabeled“csrfmiddlewaretoken”,whichwillprovideyouthekeyandvalue:

CreateYourCodeNowthatyouknowtherequirements,youcannowcreatetheprogramthatyouneedtobuildyourdictionary:

Savethisaslogin_scraper.pyandthenrunitontheinterpreterprompttogetthecredentialsthatyouneed.

Chapter10:UnderstandingAttacksUsingPython

Hackingisnotallaboutlaunchingattacks–understandinghowblackhathackerslaunchtargetandpenetratetheirtargetsystemswillmakeyouunderstandhowyoucanuseyournewfoundknowledgetopreventyourownsystemfrombeingvulnerabletothem.

KnowingUserLocationsOutofTweetsIfyouhavebeenusingTwitter,youmaythinkthatyouaretweetingyourupdatesfromsheerrandomness;however,thetruthisthatyouarefollowinganinformalformulaforthetweetsthatyoucompose.Generally,thisformulaincludesanotherTwitteruser’snamewhichtellstowhomyourtweetisdirectedto,thetextofyourtweet,andyourchoiceofhashtag.Thereareotherdataincludedinyourtweet,whichmaynotbevisibleinthebodyofyourtweet,suchasanimagethatyouwanttoshareoralocation.Toahacker,alltheinformationinyourtweetcontainssomethingthatwillbeimportantinwritinganattack–whenyouthinkaboutit,youaregivingawayinformationaboutthepersonthatyouareinterestedin,linksthatyouandyourfriendarelikelytobeinterestedin,andtrendsthatyoumightwanttolearnabout.Thepictures,especiallyanimageofalocation,becomeaddeddetailstoauser’sprofile,whichforexamplemayindicatewhereatargetedpersonislikelytogotoeatbreakfast.

Ifyouwanttogetdetailsanonymouslytoretrievealltheseinformation,youcanusethefollowingcode:

Now,youcantestthisscriptbycreatingalistofcitiesthathostmajorleagueteams.AfterthatyoucanscrapeTwitteraccountsforWashingtonNationalsandtheBostonRedSox.Yourscriptwilllooklikethis:

Whenyourscriptreturnswiththeaboveresults,youarelikelytodeducethatthetheseteamsaretweetinglivefromwheretheyare.Fromthisoutput,youmaydeducethattheRedSoxareplayinginToronto,whiletheNationalsareinDenver.

MatchinganIPAddresstoaPhysicalLocationMostofthetime,peoplearewillingtopostwhatisontheirmindonsocialmediasites,orperformattacksthattheyfindusingonlinetoolsthattheycandownload,thinkingthattheywillneverhavetofacetheconsequencesoftheiractions.Whilemostbullheadedyetinexperiencedhackersandonlinetrollsthinkthattheycanhidebehindafakeaccounttoconcealtheiridentity,youcanprovethatthesepeoplearenotasanonymousastheythinktheyare.Infact,thereareseveralwaystouselibrariesandthird-partymodulesinPythontounmaskthelocationandidentityofauserbasedonhisorherIPaddress.

Forexample,yoususpectthatyoursystemisbeingtargetedbyanotherhackerandyounoticethatyouropenportsarebeingsniffedbyaparticularIPaddress.WhatyouwillwanttodoonceyourealizethispotentialattackistoidentifythatIPaddress’locationandreportittotheauthorities.Pythoncanhelpyoudothatusingascriptthatissimilartowhatisgoingtobediscussedinthissection.

Inthisexample,youwillbeusingthefreelyavailabledatabasethatcanbefoundinhttp://www.maxmind.com/app/geolitecity.Usingthisfreedatabase,youwillaimtowriteacodethatwillmatchtheIPaddressesfoundontheirlisttocities.Todothat,downloadthefreedatabase,decompressit,andsendittothelocation/opt/GeoIP/Geo.dat.

OnceyouareabletodownloadtheGeoCityLitedatabase,youwillbeabletoanalyzetheIPaddressesdowntolocatingthecountryname,state,postalcode,andagenerallongitudeandlatitude.Tomakethejobeasier,youcanuseaPythonlibrarycreatedtoanalyzethisdatabase.

Whenyourunthisscript,youwillbeabletoseedatathatlookslikethis:

ParsePacketswithDpktAtthispoint,youunderstandhowimportantitistoanalyzepackets–youwillnotonlywanttoanalyzethepacketsthatarecomingfromanothercomputertounderstandanotheruser’sactivities,butalsounderstandwhatotherpeoplearegoingtodowiththepacketsthattheyareobservingfromyourcomputer.Inthishack,youwilllearnhowtoanalyzeanetworkcapture,andexaminetheprotocollayerofeachpacketusingthetoolcalledDpkt.

Whenyourunthisscript,youwillbeabletofindboththesourceanddestinationIPaddresses:

ThenextthingthatyouwillwanttodoistomatchtheseIPaddresseswithaphysicallocation.YoucanimprovethescriptthatyouhavejustcreatedbycreatinganadditionalfunctionretGeoStr(),whichwillgiveyouaphysicallocationfortheIPaddressthatyourcodeisabletolocate.Forthisexample,youwillbeabletofindthethree-digitcountrycodeandthecityforeachIPaddressandthenhavethecodedisplaythisinformation.Justinanycasethefunctionpromptsyouwithanexception,handleitbyprovidingamessagethatindicatesthattheaddressisnotregistered.ThiswillallowyoutohandlealladdressesthatarenotincludedintheGeoLiteCity

databasethatyoudownloadedearlierorinstancesofprivateaddresses.

OnceyouareabletoaddthefunctionretGeostrtothescriptthatyouwereabletoproduceearlier,youwillbeabletocreateagoodpacketanalysistoolkitthatwillallowyoutoviewthephysicaldestinationsofpacketsthatyouwanttostudy.Thisishowyourfinalcodeshouldlooklike:

Thisishowyourscriptwilllooklikeinaction:

Basedontheseresults,youknowthatthetrafficthatyouareanalyzingisroutedtodifferentpartsoftheworld.Nowthatyouareawarethatyourdataispossiblybeingroutedtotoomanydifferentcomputers,yougettheideathatyouneedtoimproveyoursecuritybysecuringyourports.

ARPPoisoningUsingPythonIfyouareahacker,oneofthethingsthatyouwillwanttoensureisyouranonymity.Youwillwanttomakesurethatyourlocationisuntraceable,andthatisbecauseofagoodnumberorreasons.Forthesakeofpracticingwhitehathacking,youwillwanttolearnhowprogrammersareabletomasktheirlocationespeciallywhentheyperformreconnaissanceattacksorDoSattacks,whichmakesuseoftheInternetProtocolandseetoitthatyoucheckyourtrafficfromtimetotimetoseeifyouractivitiesarebeinglistenedtobyanunknownIPaddress.Atthesametime,youmayalsowanttoprotectyourselffrombeingtargetedbyblackhathackersbyhidingyourlocation.

Toblackhathackers,IPspoofingessentiallyletsthemconcealtheiridentityandlocationwhenevertheyperformtheirattack.DoingsowillalsoallowthemtoimpersonateanothercomputersystemanddefeatexistingsecuritymeasureswhichmayrequireauthenticationbasedontheirIPaddresses.

OneoftheattacksthatmakesuseofusingfalsifiedIPiscalledARPspoofing,whichinvolvessendingafalseAddressResolutionProtocol(ARP)messageoveratargetedlocalareanetwork.Whendonesuccessfully,anattacker’sMACaddressgainstheIPaddressofanauthorizedcomputeroverthetargetednetwork.Thiswillallowanattackertomodifyorstopalltraffic,orinterceptdatasentoverthenetwork.Usingthefollowingcode,youcancatchallpacketsthatareroutedtowardsatargetedmachine,whichentailsbeingabletoseealltheinformationthatatargetedusersendsout,whichallowsyoutoviewprivatecommunicationthatisnotprotectedbyanyformofencryption.

FindInformationAbouttheTargetedMachineTofindouthowyoucanhackyourtarget,youwillneedtochecktheARPcacheonthemachinethatyouwanttoattack.ToinspectfortheARPcacheonaWindowsmachine,takealookatthisexample:

Youwillnoticethatthetarget’sdefaultgatewayIPaddressisat172.16.1.254andhasanARPcacheentrywiththeMACaddress3c-ea-4f-2b-41-f9.TakenoteofthistochecktheARPcachewhileyouhaveanongoingattackandverifythatyouhavechangedtheMACaddressthatcorrespondstothegateway.

CodetheAttackNowthatyouknowthetarget’sIPaddressandthegateway,youcannowcreateyourcode.Yourcodeshouldlooklikethis:

CodethePoisoningThecodeabovesetsupyourattackbyinputtingthetargetIPaddressandtheMACaddressthatgoeswithitusingtheget_macfunction.Youhavealsosetupapacketsnifferthatwillcapturetrafficforyourtargetedmachine.AllthatisleftforyoutodoistowritethesepacketsouttoaPCAPfilethatyoucanpulluplaterusingtheWiresharktool,oruseanimagecarvingscript.Oncethatisdone,youcancallthefunctionrestore_target,whichwillallowyoutoputthenetworkbacktoitsoriginalformbeforetheattackhappened.

Nowthatyouareabletosetupthehack,youarenowreadytocodetheARPpoisoning.Putthefollowingcodeabovethecodeblockthatyoureadearlier:

Chapter11:OtherNiftyHackstoTry

PreventDetectionbyAntivirusAnantivirussoftwareisdesignedtodetectsuspiciousfilesinyoursystem,suchasvirusesandmalwares.However,beingabletomodifythecontentsofamalwarewillenableyoutobypassantivirusdetection.

Inthishack,youwillbeabletolearnhowtocreateamaliciouscodeusingaKaliLinuxcomponentcalledMetasploit.Thisprogramcangeneratemalware,butmostoftheantiviruscompaniescaneasilyrecognizecontentwrittenbythissoftwarewhentheyarereleasedintoacomputerastheyarewrittenoriginally.Inordertocreateanantivirus-proofmalware,youwillneedtotweakthemalwarethatyouwillcreateusingsoftware.

CreateYourMaliciousProgramPullupKaliLinuxandlaunchaterminal.Runthiscommand:

mfspayload-1|more

Doingsowilldisplayexploitsthatareavailableforyoutouse,suchasthefollowing:

Ifyouwanttobindashellinordertocreateaportlistener,executeacommandinatargetedport,andcreateyourownremotecontrol,enterthesecommandsintheKaliLinuxterminal:

msfpayloadwindows/shell_bind_tcpX>shell.exe

ls-lshell.exe

Youwillgetthefollowingoutput,whichshowsthatMetasploithascreatedanexecutablefilenamedshell.exe,whichisyourmalware:

Ofcourse,anysensibleantivirussoftwarewillrealizethatthisisaninsecurefilewhichmaycompromiseatarget’scomputer.

TestYourMalwareToseethatthe.exefilethatyouhavecreatedisrecognizedasamalware,transferittoanothercomputerthathasanantivirusprogramviaaUSB,email,ordragitontothedesktoptocopy.Almostimmediately,theantivirusinstalledwillcatchit,anddetectitlikethis:

Now,ifyouaregoingtoturnofftheantivirussoftwareandrunthemalware,thecommandlinewilldisplaysomethinglikethis:

Whenthishappens,youcanactuallycontroltheWindowsmachinewherethemalwareisinstalledusinganothercomputer.

Tostopthemalware,endtheshell.exefileinTaskManagerorrestartthePC.

EdittheMalwareUsingPythonSinceyourantivirusprogramcandetectthemalwareyoucreated,youneedtoeditthemalwarecodeinorderforittobypassyourcomputer’ssecurity.Todothat,pullupKaliLinuxandtypethiscommandstringintheterminal:

mfspayloadwindows/shell_bind_tcpC

Youwillseethecodefortheexploitthatyoupreviouslyrantobeinhexadecimalcode.Whatyouneedtodoistocompilethiscodeintoan.exefile.Todothis,allyouneedtodoisinputthiscommandstringinaKaliLinuxterminal:

mfspayloadwindows/shell_bind_tcpC>shell

ls-lshell.py

Uponenteringthiscode,KaliLinuxwillgenerateafilewhichlookslikethis:

ThiscodeisinClanguage,whichmeansthatyouwillneedtoaddsomelines.Todothat,enterthiscommandstringintheKaliLinuxterminal:

nanoshell.py

Youwillgetatexteditorwiththiscode:

Importthesystem’slibrarycodethatwillenableyoutorunCprogramsfromPython.Todothat,addthefollowinglineatthebeginningofthecode:

fromctypesimport*

Addthefollowingtothebeginningoftheinitialhecadecimalcodeline:

shellcode=(

Afterthat,removethefollowingline:

Unsignedcharbuf[]

Yourcodeinthenanotexteditorshouldappearlikethis:

Scrolldownandfindthesemicolonlocatedneartheendofthescript.Addaclosingparenthesisbeforeit.Afterdoingso,addthefollowinglinesattheendofthecode:

Youshouldseethisonyourscreenafterdoingso:

Tosaveyourfile,pressCtrl+X,andthenpressYattheprompt.Entertoproceedsavingyourmodifiedfile.

CompiletheMalwareandRunItInordertorunthemodifiedmalware,youwillneedtocompileitfirst.Todothat,pullupa

commandpromptandthenrunthiscommandstring:

pyinstaller--onefile--noconsoleshell.py

Thiswillcreateanewfolderthatisnamed“dist”.Thisfolderwillhavethemodifiedmalwareinsideitnamedasshell.exe.Torunthemalware,allyouneedistoopenthefolderanddouble-clickontheshell.exefile.

TheWindowsFirewallmightblocksomeoftheprogram’sfeaturessinceitwillattempttoconnecttoaremoteserver.BypassthatbyselectingAllowAccess.Afterdoingso,pullupthecommandpromptandthenrun:

netstat-an|findstr4444

Thiswillpullupalisteningport,whichlookslikethis:

Tostopthelistener,simplypulluptheTaskManagerandendtheprocessesnamedshell.exe.

Checkwithyourantivirusifthemalwarethatyouhavejustcreatedcanstillbedetected.Itshouldbypassmostoftheknownantivirusprogramsoutthere.

RetrieveDeletedItemsinRecycleBinAsyoualreadyknow,theRecycleBininWindowsOSisusedasaspecialfolderthatservesasstorageforfilesthatauserdeletes.Thesefilesaremarkedtobeerasedfromtheharddrive,buttheyarenotactuallyremoved.InolderWindowsoperatingsystems(Windows98andolder),thesefilesarestoredinthedirectoryC:\Recycled,andsubsequentoperatingsystemsuntilWindowsXPstorethesefilesinadirectorynamedC:\Recycler.IfyouareusingWindows7andVista,yourfilesarestoredatadirectorynamedC:\$Recycle.Bin.

IfyouemptyyourRecycleBin,youmaythinkthatallthefilesthataremovedtherearecompletelygone.However,therearesituationswhereinyoumaywanttorecoverfilesthatyouaccidentallydeletedfromtheRecycledBin,oryoumaywanttogodumpsterdivingandrecoverimportantdocumentsthatweredeletedfromatargetcomputer.Thiscodewillhelpyoudoallthesethings.

CreateaModuleToHelpFindDeletedFilesOfcourse,youwillwanttowriteascriptthatwillbeindependentoftheoperatingsystem,whichwillmakeitusefultohackadifferentoperatingsystem.Todothat,youwillwanttowriteafunctionthatwillrunatestagainstallpossibledirectoriesthatcontainsdeletefilesinanoperatingsystem,andthenreturnwiththeinformationthatcontainsthedirectorythatexistsontheoperatingsystemthatyouwishtoexploit:

OnceyoumanagetofindthetargetedRecycleBindirectory,thenextthingthatyouwanttodoistolookatthecontents.Takealookatthefounddirectory:

YouwillnoticethestringsS-1-5-21-1275210071-1715567821-725345543-whichendswitheither500or1005.Thesestringsrepresenttheuseraccountsonthetargetedmachine.Now,youwillwanttoidentifytheseuseraccountsandfindoutwhichoftheuseraccountsyouwillwanttoretrievethedeleteditemsfrom.

ChecktheUserIDTodecodetheSIDstringthatyoufoundearlier,youwillneedtoaccesstheWindowsRegistryandmatchthestringwithausername.Youwillfindtheinformationwiththisregistrykey:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsNT\CurrentVersion\ProfileList\<SID>\ProfileImagePath

Pullupyourcommandprompt,andtypein“regquery”.Thiswillcomeupwiththisresult:

Adterdecodingtheusername,youwillneedtocreateafunctionthatwilltranslatetheSIDintotheuser’sname.DoingsowillallowyoutogetmoreusefulinformationwhenyourecoveritemsthatweredeletedfromtheRecyleBin.

ThisfunctionwillpulluptheregistrytochecktheProfileImagePathKey,searchforthevalueandthensendbackwiththenamethatisfoundrightafterthebackslashinthetargetuserpath.

Now,it’stimetoputtheentirecodetogetherthatwillrevealallthefilesthatarestillintheRecycleBin.Thisishowthecompletecodewilllooklike:

Whenyourunthiscodeinsidethetargetedmachineintheexample,youwillnoticethatthescripthasfoundtwousers,theAdministratorandalex.Youwillalsobeabletoseesomeofthefilesthatweredeletedthatyoumaywanttoretrieve:

CreateaKeyloggerUsingPythonKeylogging,alsoknownaskeyboardcapturingorkeystrokelogging,isatrickusedbyhackerstorecordthekeysthatarepressedonakeyboardwithoutthevictimknowingthatheisbeingrecorded.Bybeingabletorecordthesekeystrokes,anyhackerwillbeabletodecipherhowthetargeteduserinteractswithhiscomputer.Thismeansthatwithakeylogger,youessentiallyhaveaccesstopracticallyeverythingthatthevictimhastypedonhiskeyboard,whichincludessensitivedatasuchasusernames,passwords,creditcardnumbers,andsoon.Creatinganefficientkeyloggerwillenableyoutoconvenientlystealsomeoneelse’sidentity,especiallywhenyourloggerremainstobeundetected.

Despitethehugedangerthatkeyloggersmayposetoanyuser,theyareremarkablyeasytomakeusingPython.Thecodethatwillbetaughtinthissectionisakeyloggerthatdoesnotrelyonhardwareandwillcontinuetoruninthebackground,whichpreventsthetargeteduserfromnoticingit.

PullupYourEditorOpenIDLE,oranytexteditorofyourchoice.Onceyouareonanewscriptwindow,inputthefollowingcode:

TesttheCreatedFileSavethecodeaskeylogger.py,andthenrunthefilebypressingCtrl+R.Thekeyloggerwillproceedrunninginthebackgroundandwilllogthekeystrokesonthekeyloggeroutput.txtfile.

Toendlogging,pullupTaskManagerandendallrunningPythontasksandprograms.

Conclusion

Atthispoint,youmayhavehadsomeideaonhowyoucanmakeyourowncomputersystemandnetworkmore secure – simplyperforming someof the codes that are given in this book as anexamplewillgiveyoutheideathattherearejusttoomanyexploitsouttherethatareavailabletocriminalhackersandareusedtocompromisetargetedcomputers.However,yournewknowledgecanpreventyoufromfallingvictimtothesehackersandallowyoutothinktenstepsahead.Sinceyoualreadyaredonereadingabeginner’sguidetohackingwithPython,theonlynextstepsthatyouneed todo is tohoneyour skillsby improvingopen-source scripts andcreatingyourownprogramsthatyoucansharetootherpeoplethatareinterestedininformationsecurity.

NowthatyouhavebetterknowledgeabouthowcriminalhackershackusingPython,youcanfinetunethatknowledgeintodevelopingprogramsthatwillmitigatetheseattacks.Takenotethatthehacking tools that were discussed here are also tools that can help you discover your ownvulnerabilities that hackers can exploit. Since you are capable of using the sameprogramminglanguage thatmany sophisticatedhackersusenowadays, youhave theopportunity to stop themwithbetterscriptsandprogramsthatyoucanalsosharetoyournetwork.

If you have enjoyed reading this book and you believe that you have become a better hackerbecauseofit,pleasetakethetimetosharethisbooktofellowhackersandtellotherreadersaboutitonAmazon.com.Iamexcitedtohearfromyousoon!

Bonus:PreviewOf‘IntroductiontoPython3Pythonisaprogramminglanguageusedfor interactive,portableandflexibleprograms.Ithasasyntax thatcaneasily interfacewithother systems. It’sobject-oriented,meaning, it focusesonobject-orienteddata,modulesandclasses.Youcanuseitforgeneralpurposesinprogramming.Ithasalsoabroadrangeofstandardlibrarythatallowsyoutoworkquicklyandmorereliably.

ThefirstversionsofPythonarethe2xseries,whichisstillveryusefulevenwiththeadventofthe3xseries,becauseitsfeaturesarecompatiblewithmoreapplicationsandsystems.Becauseofsomeupdates,thePython3seriesisstillnotacceptedbyotherdevices.TherearesomesystemsthatarenotadjustedtoPython3.

Nevertheless,Python3isthelatestseriesofthePythonprogramminglanguage.JustlikePython2,it’seasiertolearnthanmostprogramminglanguagesbecauseitssyntaxisclearandsimpleandnotdifficult,unlikethestaticallytypedlanguages.

Pythonhas also an interactive interpreter, such as IDLE to allow learners to codequickly andcheck-atthemoment-iftheirsyntaxesarecorrect.

Forthisbook,wewillbefocusingonthePython3series.

ClickheretocheckouttherestonAmazon.