![Page 1: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/1.jpg)
![Page 2: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/2.jpg)
HackingwithPython
TheUltimateBeginner ’ sGuide
![Page 3: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/3.jpg)
IntroductionThisbookwillshowyouhowtousePython,createyourownhackingtools,andmakethemostoutofavailableresourcesthataremadeusingthisprogramminglanguage.Ifyoudonothaveexperienceinprogramming,don’tworry–thisbookwillshowguideyouthroughunderstandingthebasicconceptsofprogrammingandnavigatingPythoncodes.Thisbookwillalsoserveasyourguideinunderstandingcommonhackingmethodologiesandinlearninghowdifferenthackersusethemforexploitingvulnerabilitiesorimprovingsecurity.YouwillalsobeabletocreateyourownhackingscriptsusingPython,usemodulesandlibrariesthatareavailablefromthird-partysources,andlearnhowtotweakexistinghackingscriptstoaddressyourowncomputingneeds.ThankyouandIhopeyouenjoyit!
![Page 4: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/4.jpg)
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.
![Page 5: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/5.jpg)
TableofcontentsChapter1:PreparationForHacking
Chapter2:PythonBasics
Chapter3:WritingPythonPrograms
Chapter5:OperatorsandExpressions
Chapter6:FunctionsandModules
Chapter7:SettingUpforHacking
Chapter8:NetworkHacking
Chapter9:HacksfortheWeb
Chapter10:UnderstandingAttacksUsingPython
Chapter11:OtherNiftyHackstoTry
Conclusion
Bonus:PreviewOf‘IntroductiontoPython3
![Page 6: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/6.jpg)
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.
![Page 7: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/7.jpg)
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.
![Page 8: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/8.jpg)
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:
![Page 9: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/9.jpg)
InstallingonLinuxIfyouroperatingsystemisGNU/Linux,youcanuseUbuntuorDebiandistributionmanagertoinstallPython.Todothat,simplykeyinthiscommand:
Onceyouareabletoinstalltheprogram,runitbytyping“python”ontheterminal.
![Page 10: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/10.jpg)
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
![Page 11: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/11.jpg)
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
![Page 12: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/12.jpg)
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
![Page 13: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/13.jpg)
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
![Page 14: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/14.jpg)
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
![Page 15: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/15.jpg)
isnotatexteditorthatisdevoidofbellsandwhistles–itcomeswithfeatureslikeSSHconnectivity,codecontrolstoconnectautomaticallytoahub,andaTerminalinterface.Ifyouaregunningtodevelopawebappforyourhacks,thenthisisprobablytheIDEthatwillworkbestforyou.
Nowthatyouhaveyourdevelopmentenvironmentsetup,it’stimeforyoutostartlearningaboutPython’sbasicconcepts.
![Page 16: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/16.jpg)
Chapter2:PythonBasicsYourgoal,ofcourse,istomakePythongobeyondprintingatext.Todothat,youwillneedtolearnotherconceptsthatareessentialinaPythonscript.Youwillalsowanttocreateascriptthatiseasyforyoutounderstandandreviewinthefuture,justinanycaseyouwanttoimproveitandturnitintoaworkingtoolforyourhacks.
Inordertotakeinputsandmanipulatetheminordertogetcertainresults,youwillfirstneedtolearnhowvariablesandconstantsworkinthisprogramminglanguage.
![Page 17: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/17.jpg)
CommentsThesearestatementsthatcomeafterthe#symbol.Thesepiecesoftextsallowyouto:
Explaintheproblemsthatyouareaimingtoovercomeorsolveinyourprogram
Takenoteoftheimportantassumptions,details,anddecisionsthatyouwanttoperforminthecode
Makingnotesinyourcodedoesnotonlyremindyouwhatyouwanttoachieveinyourcode,butalsohelpreadersthatwillbeusingyourprogramunderstandwhatlinesofcodearesupposedtodo.
![Page 18: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/18.jpg)
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:
![Page 19: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/19.jpg)
Thispieceofcodewillgiveyouthisresult:
![Page 20: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/20.jpg)
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.
![Page 21: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/21.jpg)
ObjectsThingsthatarereferredtoasanythinginthecodethatexistsinPythonarecalledobjects.IfyouaremigratingtoPythonfromanotherprogramminglanguage,youneedtotakenotethateverythinginPython,includingstring,numbers,andfunctions,isclassifiedasanobject.
![Page 22: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/22.jpg)
ListsPythonallowsyoutomakeuseofalistdatastructurewhichisextremelyusefulwhenitcomestostoringcollectionsofobjects.Asaprogrammer,youcancreateliststhatcontaindifferenttypesofdata.Atthesametime,youcanalsomakeuseofseveralbuilt-intechniquesinPythonthatwillallowyoutoinsert,index,count,sort,append,remove,pop,andevenreverseitemsinalist.Takealookatthisexample:
Usingtheabovecode,youwereabletocreatealistthroughthemethodappend(),printallthespecifieditems,andthenmanagetosorttheitemsbeforeyouaskedtheprogramtoprintthemagain.Youwerealsoabletofindanitem’sindexandalsoremoveparticularitems.
![Page 23: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/23.jpg)
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.
![Page 24: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/24.jpg)
Chapter3:WritingPythonProgramsNowthatyouareawareofsomebasicconceptsthatyouneedtograspinPython,it’stimetolearnsomeguidelinesthatyouneedtorememberwhenitcomestowritingaPythonprogram.Inthischapter,youwilllearnhowtousesomeofthemostbasicconceptstorunsimplecommandsandformatyourPythoncodesinsuchawaythatitwillbeeasierforyoutounderstandanddocumentthemlater.
![Page 25: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/25.jpg)
HowtoUseLiteralConstantsandVariables
Pullupyourtexteditorandrunthefollowing:
Youroutputshouldlooklikethis:
Whathappenedinthisprogramisthatyouassignedaliteralvalueof5tothegivenvariableithroughanassignmentoperator,whichisthe=sign.Thatentirelineisconsideredastatementbecauseitindicatedthatsomethingshouldbedone,whichisconnectingthesaidvariabletoanumericalvalue.Afterwards,youprintedoutthevalueofibyusingtheprintcommand.
Afterwards,youadded1tothegivenvaluethatyoustoredinthevariablei,andthenyousavedit.Whenyouusetheprintstatementagain,yougetthevalueof6.
Atthesametime,youalsoassignedaliteralstringtothevariablesandthenproceededtousetheprintstatement.
![Page 26: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/26.jpg)
PhysicalandLogicalLinesWhatyouseewhenyoutypeoutaprogramiscalledaphysicalline.WhatPythongetswhenyoutypeastatementiscalledthelogicalline.Withthissaid,thisprogramminglanguageassumesthateveryphysicallinethatyouseecorrespondstoagivenlogicalline.
Whileyoucanusemorethanonelogicallineonaphysicallinebyusingthesemicolon(;)symbol,Pythonencouragesthatprogrammerslikeyouinputasinglestatementinordertomakeyourcodesmorereadable.Thisway,youwillbeabletoseelinesthatyouareworkingonandavoidpossibleconfusionwhenyouareworkingontwodifferentlogicallinesandgetlostonwhatyouaresupposedtoworkon.
![Page 27: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/27.jpg)
IndentationPythonisoneoftheprogramminglanguagesouttherewherewhitespace,especiallythespaceatthebeginningofeachlineofcodeisimportant.Byusingindentation,youcangrouptogetherblocks,orstatementsthatbelongtogether.Asaruleofthumb,seetoitthatyouareusingthesameindentationwhenyouareworkingonsimilarstatements.Alsorememberthatusingthewrongindentationcanmakeyourcodepronetoerror.Takealookatthisexample:
Whenyourunthiscode,youwillgetthisresult:
Pythonrecommendthatyouusefourspacesforyourindentations.Typicalgoodtexteditorswilldothisforyou.Aslongasyouareconsistentwiththespacesthatyouareusing,youwillbeabletoavoidunexpectedresultsinyourcode.
Nowthatyouknowthebasics,youcannowstartlearningthemoreinterestingstuff!
![Page 28: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/28.jpg)
Chapter5:OperatorsandExpressionsMostofthestatements(alsocalledlogicallines)thatyouwillbewritinginyourcodewillincludeexpressions.Expressionsaredividedintooperandsandoperators.
Operatorsareessentiallyfunctionsthatdosomethinginyourcode,whicharerepresentedbysymbolsorkeywords.Theyusuallyrequirepiecesoninformationthattheycanworkon,whicharecalledoperands.Forexample,ifyouhavetheexpression4+5,theplus(+)signistheoperator,andthenumbers4and5areoperands.
![Page 29: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/29.jpg)
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:
![Page 30: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/30.jpg)
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
![Page 31: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/31.jpg)
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
![Page 32: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/32.jpg)
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!
![Page 33: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/33.jpg)
Chapter6:FunctionsandModulesWritingacodeforhackingcanbetediouswhenyouarelimitedtousingoperations–justimaginehavingtowriteanoperationandthenrepeatthatoverandoveragainthroughoutyourscriptinorderforyourcodetodosomething.ItisagoodthingthatPythonallowsyoutomakeuseoffunctionsandmodulesthatwillallowyoutorepeatcertainactionswithinyourcodeandinotherscriptsthatyouwillbebuildinginthefuture.
Inthischapter,youwilllearnhowtocreateandmakeuseoffunctionsandmodules.Youwillalsolearnhowtoiteratecommandsthatyouhaveissuedinyourscriptinordertorepeatcertainactionsfordifferentelements,andhandleerrorsthatyoumayencounterinyourscript.
![Page 34: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/34.jpg)
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:
![Page 35: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/35.jpg)
Savethisasfunction_param.pyandthenrunitattheinterpreterprompt.Youshouldgetthisoutput:
KeywordArgumentsTherewillbeinstancesasyoucodewhereinyouhavetoomanyparametersinyourfunction–ifyouwanttospecifysomeofthem,thenyoucanusekeywordargumentsinordertogivevaluesforsomeoftheparameters.Doingsowillgiveyoutheadvantageofeasilyusingthefunctionwithouthavingtoworryaboutthearguments’order,andthatyoucanassignvaluestotheparametersthatyouwanttouse,especiallywhentheotherparametersthatareavailablealreadycontainsargumentvaluesthataresetindefault.
Takealookatthissamplecode:
Savethiscodeasfunction_keyword.py,andthenrunitattheinterpreterprompt.Youshouldgetthefollowingoutput:
ThereturnStatementIfyouwanttobreakoutofthefunction,orifyouwanttoreturnavaluefromthefunction,thenthisstatementwillprovetobehelpful.Takealookatthisexample:
![Page 36: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/36.jpg)
Savethiscodeasfunction_return.pyandthenrunitattheinterpreterprompt.Youshouldgetthefollowingoutput:
DocStringsPythoncomeswithacoolfeaturecalleddocstrings,whichisatoolthatyoucanusetodocumentthecodethatyouarecreatingandmakeiteasiertounderstand.Youcanalsogetadocstringfromafunctionwhilethecodeisalreadyrunning.Takealookatthisexample:
Savethiscodeasfunction_docstring.pyandthenrunitontheinterpreterprompt.Youshouldgetthefollowingoutput:
Whathappenedhereisthatyouareabletoviewthedocstringforthefunctionthatyouhaveused,whichisthefirststringontheinitiallogicalline.Takenotethatdocstringscanalsobeusedinclassesandmodules.
![Page 37: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/37.jpg)
IterationTherearesomeinstanceswhereinyoumayfindittoredundanttowritethesamecodemultipletimestodoasimilarfunction,suchascheckingdifferentIPaddressesoranalyzedifferentports.Forthisreason,youmaywanttouseafor-loopinsteadtoiteratethesamecodefordifferentelements.Forexample,ifyouwishtoiterateacodeforthesubnetofIPaddressesfrom192.168.0.1through192.168.0.254,youcanuseafor-loopthatcontainsarangeof1to255todisplaytheentiresubnet.Takealookatthissamplecodetoseehowitisdone:
Ifyouwanttoiteratethesamecodethroughalistofknownportstoanalyzeasystem’svulnerabilities,youcaniteratethroughalistofelementsthatyouwanttocheckinstead.Takealookatthisexample:
![Page 38: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/38.jpg)
ExceptionHandlingEvenifyouarealreadyabletowriteaprogramwithcorrectsyntax,youmaystillgothroughsomeerrorsuponexecutionorruntime.Forexample,whenyoudivideanythingbyzero,youarelikelytoexperiencearuntimeerrorbecausePythonknowsthatitisimpossibletodoso.Whenyouattempttoperformthisaction,Pythonmightreturnwiththisoutput:
Ifyouwanttofixtheerrorwhileyouarealreadyrunningyourcode,Python’sabilitytoperformexceptionhandlingwillcomeinhandy.Usingtheexampleabove,youcanusethetryorexceptstatementinordertomakeuseoftheexceptionhandlingsothatwhentheerrorhappens,theexceptionhandlingfeaturewillcatchtheerrorandthenprintthemessageonthescreen.Takealookatthisexample:
Ifyouwanttoseewheretheerrorspecificallyhappenedinyourscript,youcanusethefollowingcodeinstead:
![Page 39: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/39.jpg)
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.
![Page 40: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/40.jpg)
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:
![Page 41: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/41.jpg)
![Page 42: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/42.jpg)
ThePythonStandardLibraryPython’libraryisprettymuchthecollectionofalmosteveryelementthereisinthisprogramminglanguage.Thisextensivecollectioncontainsseveralbuilt-inmodulesthatallowyoutoaccessdifferentfunctionalitiesinthesystem.ThePythonsstandardlibraryisalsoresponsibleforprovidingyouaccesstomodules,whicharedesignedtoenhancePython’sinherentportability.Thismeansthatyouareabletodealawaywithplatformswhenitcomestocreatingyourcodes.
IfyouarerunningPythonfromaWindowsmachine,youarelikelytohavetheentirestandardlibraryincludedinyourinstallation.IfyouareoperatingusingUNIXoranysimilaroperatingsystem,youmayneedtousethepackagingtoolsavailableinyouroperatingsystemifyouwanttogetsomeoftheoptionalcomponents.
Atthispoint,youalreadyknowtheessentialsinPython.Asyoucreateyourowncodesforhackingorimportmodulesfromlibraries,youwillbeabletodiscovermorefunctionalitiesandlearnwhattheyarefor.
Sinceyouarelearninghowtocodeinordertohack,thebestwayforyoutopickupyourpaceistolearnasyoucreatetoolsthatyoucanuseforhacking.Thismeansthatitistimeforyoutodotheexcitingstuff!
![Page 43: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/43.jpg)
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.
![Page 44: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/44.jpg)
InstallingThirdPartyLibrariesThirdpartylibrariesareessentiallylibrariesthatdonotcomenativewithyourinstallationofPython.Allyouneedtodotogetthemistodownloadthemfromatargetedsource,performuncompressingonthepackagethatyoujustdownloaded,andthenchangeintothetargetdirectory.
Asyoumighthavealreadyguessed,thirdpartylibrariesareextremelyusefulwhenitcomestodevelopingyourowntoolsoutoftheresourcesthatarealreadycreatedbysomeoneelse.SincePythonisahighlycollaborativeprogramminglanguage,youcanuselibrariesthatyoumayfindfromwebsitesourcessuchasGitHuborthePythonwebsiteandincorporatethemintoyourcode.There
Onceyouareinsidethedirectory,youcaninstallthedownloadedpackageusingthecommandpythonsetup.pyinstall.Takealookatthisexampletoseehowitisdone:
Whatjusthappenedhereisthatyouwereabletoinstallapackagethatwillallowyoutoparse
![Page 45: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/45.jpg)
nmapresultsbydownloadingthepython-nmappackage.
Tip:Ifyouwanttoestablishyourdevelopmentenvironmentfaster,youmaywanttogetacopyoftheBackTrackLinuxPenetrationDistribuion,whichessentiallyallowsyoutogetaccesstotoolsthatareusedforforensics,networkanalysis,penetrationtesting,andwirelessattacks.
![Page 46: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/46.jpg)
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
![Page 47: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/47.jpg)
correspondingusername.Afterthat,themainfunctionwillcallthetestPassfunctiontotestthehashedpasswordsagainstthedictionary.
ThetestPassfunctionwilltakethepasswordthatisstillencryptedasaparameterandthenwillreturnafterexhaustingthewordsavailableinthedictionaryorwhenithassuccessfullydecryptedthepassword.Thisishowtheprogramwilllooklike:
Whenyourunthiscode,youwillbeabletoseethisoutput:
![Page 48: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/48.jpg)
Judgingfromtheseresults,youwillbeabletodeducethatthepasswordfortheusername‘victim’isrightinthedictionarythatyouhaveavailable.However,thepasswordfortheusername‘root’isawordthatyourdictionarydoesnotcontain.Thismeansthattheadministrator’spasswordinthesystemthatyouaretryingtoexploitismoresophisticated,butcanpossiblybecontainedinanotherdictionarytype.
Atthispoint,youarenowabletosetupanidealhackingenvironmentforPythonandlearnhowtomakeuseofavailableresourcesfromotherhackers.Nowthatyouareabletocreateyourfirsthackingtool,it’stimeforyoutodiscoverhowyoucanmakeyourownhackingscripts!
![Page 49: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/49.jpg)
Chapter8:NetworkHacking
Anetworkattackisanyprocessortacticthatwillallowahackertocompromiseanetwork’ssecurity.Whenyouareabletoperformanetworkattack,youcanuseauser’saccountandtheprivilegesthatareattachedtoit,stealormodifystoreddata,runacodetocorruptasystemordata,orpreventanauthorizeduserfromaccessingaservice.
Inthischapter,youwilllearnhowtoattackanetworkusingsomethird-partytoolsandcodesthatyoucanwriteusingPython.Atthesametime,youwillalsogainbetterawarenessonhowhackersgaininformationabouttheirtargetandperformattacksbasedonthevulnerabilitiesthattheywereabletodiscover.
![Page 50: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/50.jpg)
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
![Page 51: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/51.jpg)
particularnetworkingserviceduetotheportsexhaustingtheirresources.
Aportscannerwillallowyoutolookatthehostsandtheservicesthatareattachedtothem.TheyessentiallyThissectionwillenabletowriteyourownprogramforaTCPportscannerthatwillbeabletodoafullconnectscantothetarget’sTCPinordertoidentifythehoststhatyoumaywanttoexploitinthefutureusingthesocketbuilt-inmodule,whichinturngivesyouaccesstotheBSDsocketinterface.
Asyoumayhavealreadyguessed,socketsarebehindmostlyanythingthatinvolvesnetworkcommunications.Whenyoupullupawebbrowser,yourcomputeropensasocketinordertocommunicatetoawebserver.Thesamethinghappenswhenyoucommunicatetoothercomputersonline,orsendarequesttoyourprinteroveryourWi-Fi.
Takealookatsomeofthesocketfunctionsthatyouaregoingtouse:
![Page 52: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/52.jpg)
Withthisinformation,youcancreateasimpleportscannerthatwillallowyoutoconnecttoeveryportthatyouareabletodefinethatcorrespondstoaparticularhost.Pullupyourtexteditorandthensavethefollowingcodeasportscanner.py:
![Page 53: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/53.jpg)
Whenyourunthisprogramattheinterpreterprompt,thisishowtheoutputshouldlooklike:
![Page 54: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/54.jpg)
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.
![Page 55: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/55.jpg)
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:
![Page 56: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/56.jpg)
Whenyourunthiscode,youwillbeabletoseethatyouareabletobrowseawebpageusingafalseuser-agentstring.ThewebsitethatyouarebrowsingnowthinksthatyouareusingaNetscape6.01browserinsteadofsimplyusingPythontofetchthepage.
Whathappensafteristhatwebsitesthatyouaregoingtovisitwillattempttopresentcookiesthattheycanuseasauniqueidentifierinordertoidentifyyouasarepeatvisitorwhenyougobacktotheirsitethenexttime.Topreventthesewebsitesfromidentifyingyou,youwillneedtoseetoitthatyouclearallthecookiesfromyourbrowserwheneveryouperformfunctionsthatyouwanttobeanonymous.Anotherbuilt-inlibraryinPython,calledtheCookelib,willallowyoutomakeuseofvariouscontainertypesthatwillallowyoutodealwithcookiesthatwebsitepresentyou.Forthisscript,youwillbeusingacontainertypethatwillallowyoutosavecookiestodisk,andthenprintoutthecookiesthatyoureceivedduringyoursession:
![Page 57: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/57.jpg)
Whenyourunthisscript,youwillseeyoursessionIDcookieforbrowsingtheSyngresssite:
FinalizeYourAnonymousBrowserintoaPythonClassAtthispoint,youhaveanideaofallthefunctionsthatyouwanttoincludeinyouranonymousbrowser,andthatinordertomaketheentireprocessofimportingallthesefunctionstoallfilesthatyouwillbecreatinginthefuture,youwillneedtoturnthatintoaclass.Thiswillallowyoutosimplycalltheclassusingabrowserobjectinthefuture.Thisscriptwillhelpyoudothis:
![Page 58: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/58.jpg)
Thisclassnowcontainsuser-agentslist,aswillasproxyserverlistthatyoumaywanttousewhenyoubrowse.Italsocontainsthefunctionsthatyouwereabletocreateearlier,whichyoucancallindividuallyorallatonceusingtheanonymizefunction.Theanonymizefunctionwillalsoallowyoutoselecttheoptiontowaitfor60secondswhichwillincreasethetimeofrequeststhatyousend.Whilethiswillnotchangeanythingintheinformationthatyousubmittothewebsite,thisstepwilldecreasethechancethatthewebsitesthatyouarevisitingwillrecognizethattheinformationbeingsenttothemcomesfromasinglesource.YouwillalsonoticethatthefileanonBrowser.pyincludesthisclass,andshouldbesavedinalocaldirectorycontainingscriptsthatwillcallit.
Now,youcanwriteascriptwhereyoucanusetheclassthatyouhavejustcreated.Inthisexample,youwillbeenteringvotesforanonlinecompetitiononthewebsitekittenwar.comwhereyouhavetovoteforkittensbasedontheircuteness.Becausethevotesonthewebsitewillbetabulatedaccordingtoauser’ssession,youwillneedtohaveuniquevisitstothewebsitein
![Page 59: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/59.jpg)
orderforyourvotestobecounted.Usingthisscript,youshouldbeabletovisitthetargetedwebsiteanonymouslyfivetimes,whichwillallowyoutoenterfivevotesusingthesamecomputer:
Afterrunningthisscript,youwillbeabletofetchthetargetedwebpageusingfivedifferentuniquesessions,whichmeansthatyouareusingdifferentcookieseverytimeyouvisit.
![Page 60: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/60.jpg)
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
![Page 61: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/61.jpg)
IPlayer–changetheIPaddressesofthedestinationandsource
UDPlayer–changetheportsofthedestinationandsource
DNSlayer–Putinthe“answer”flag,andthenaddtheanswerthatyouhavespoofed.
Thescapemodulemakestheentireprocesssimplebyremovingawayalotofdetailsthatyoudonotneedtobeconcernedabout.Oncetheotherdetailshasbeenabstractedawaybyscapy,youcanusethefollowingcode:
Atthispoint,youhavealltheflagssetforyourattack.ThenextstepistomakeandaddtheDNSanswer:
![Page 62: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/62.jpg)
Finally,injecttheresponsethatyouhavespoofed:
![Page 63: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/63.jpg)
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.
![Page 64: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/64.jpg)
Chapter9:HacksfortheWebYoumaybewonderinghowtogetpastcertainwebsiteprotectionpoliciesinordertogetafilethatyouwant,browseanonymously,orgetmoreinformationaboutthewebsitethatyouwanttopenetrate to launchamassiveattack.Inthischapter,youwill learnhowyoucanperformCreathacksonawebsiteusingsomeprogramsthatyoucancreateusingPython.
![Page 65: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/65.jpg)
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
![Page 66: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/66.jpg)
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:
![Page 67: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/67.jpg)
Savethecodeasfabfile.pyandthenrunitontheinterpreterprompt.Thisisswhattheentirecodelookswhenyourunit:
![Page 68: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/68.jpg)
Youwillseethatyouwereabletogaincontrolofallthemachinesthatyouhaveaccessto.
![Page 69: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/69.jpg)
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:
![Page 70: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/70.jpg)
Savethisaslogin_scraper.pyandthenrunitontheinterpreterprompttogetthecredentialsthatyouneed.
![Page 71: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/71.jpg)
Chapter10:UnderstandingAttacksUsingPython
Hackingisnotallaboutlaunchingattacks–understandinghowblackhathackerslaunchtargetandpenetratetheirtargetsystemswillmakeyouunderstandhowyoucanuseyournewfoundknowledgetopreventyourownsystemfrombeingvulnerabletothem.
![Page 72: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/72.jpg)
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:
![Page 73: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/73.jpg)
![Page 74: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/74.jpg)
Now,youcantestthisscriptbycreatingalistofcitiesthathostmajorleagueteams.AfterthatyoucanscrapeTwitteraccountsforWashingtonNationalsandtheBostonRedSox.Yourscriptwilllooklikethis:
Whenyourscriptreturnswiththeaboveresults,youarelikelytodeducethatthetheseteamsaretweetinglivefromwheretheyare.Fromthisoutput,youmaydeducethattheRedSoxareplayinginToronto,whiletheNationalsareinDenver.
![Page 75: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/75.jpg)
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:
![Page 76: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/76.jpg)
ParsePacketswithDpktAtthispoint,youunderstandhowimportantitistoanalyzepackets–youwillnotonlywanttoanalyzethepacketsthatarecomingfromanothercomputertounderstandanotheruser’sactivities,butalsounderstandwhatotherpeoplearegoingtodowiththepacketsthattheyareobservingfromyourcomputer.Inthishack,youwilllearnhowtoanalyzeanetworkcapture,andexaminetheprotocollayerofeachpacketusingthetoolcalledDpkt.
Whenyourunthisscript,youwillbeabletofindboththesourceanddestinationIPaddresses:
ThenextthingthatyouwillwanttodoistomatchtheseIPaddresseswithaphysicallocation.YoucanimprovethescriptthatyouhavejustcreatedbycreatinganadditionalfunctionretGeoStr(),whichwillgiveyouaphysicallocationfortheIPaddressthatyourcodeisabletolocate.Forthisexample,youwillbeabletofindthethree-digitcountrycodeandthecityforeachIPaddressandthenhavethecodedisplaythisinformation.Justinanycasethefunctionpromptsyouwithanexception,handleitbyprovidingamessagethatindicatesthattheaddressisnotregistered.ThiswillallowyoutohandlealladdressesthatarenotincludedintheGeoLiteCity
![Page 77: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/77.jpg)
databasethatyoudownloadedearlierorinstancesofprivateaddresses.
OnceyouareabletoaddthefunctionretGeostrtothescriptthatyouwereabletoproduceearlier,youwillbeabletocreateagoodpacketanalysistoolkitthatwillallowyoutoviewthephysicaldestinationsofpacketsthatyouwanttostudy.Thisishowyourfinalcodeshouldlooklike:
![Page 78: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/78.jpg)
Thisishowyourscriptwilllooklikeinaction:
Basedontheseresults,youknowthatthetrafficthatyouareanalyzingisroutedtodifferentpartsoftheworld.Nowthatyouareawarethatyourdataispossiblybeingroutedtotoomanydifferentcomputers,yougettheideathatyouneedtoimproveyoursecuritybysecuringyourports.
![Page 79: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/79.jpg)
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:
![Page 80: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/80.jpg)
Youwillnoticethatthetarget’sdefaultgatewayIPaddressisat172.16.1.254andhasanARPcacheentrywiththeMACaddress3c-ea-4f-2b-41-f9.TakenoteofthistochecktheARPcachewhileyouhaveanongoingattackandverifythatyouhavechangedtheMACaddressthatcorrespondstothegateway.
CodetheAttackNowthatyouknowthetarget’sIPaddressandthegateway,youcannowcreateyourcode.Yourcodeshouldlooklikethis:
![Page 81: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/81.jpg)
CodethePoisoningThecodeabovesetsupyourattackbyinputtingthetargetIPaddressandtheMACaddressthatgoeswithitusingtheget_macfunction.Youhavealsosetupapacketsnifferthatwillcapturetrafficforyourtargetedmachine.AllthatisleftforyoutodoistowritethesepacketsouttoaPCAPfilethatyoucanpulluplaterusingtheWiresharktool,oruseanimagecarvingscript.Oncethatisdone,youcancallthefunctionrestore_target,whichwillallowyoutoputthenetworkbacktoitsoriginalformbeforetheattackhappened.
Nowthatyouareabletosetupthehack,youarenowreadytocodetheARPpoisoning.Putthefollowingcodeabovethecodeblockthatyoureadearlier:
![Page 82: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/82.jpg)
![Page 83: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/83.jpg)
Chapter11:OtherNiftyHackstoTry
![Page 84: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/84.jpg)
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.
![Page 85: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/85.jpg)
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:
![Page 86: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/86.jpg)
ThiscodeisinClanguage,whichmeansthatyouwillneedtoaddsomelines.Todothat,enterthiscommandstringintheKaliLinuxterminal:
nanoshell.py
Youwillgetatexteditorwiththiscode:
Importthesystem’slibrarycodethatwillenableyoutorunCprogramsfromPython.Todothat,addthefollowinglineatthebeginningofthecode:
fromctypesimport*
Addthefollowingtothebeginningoftheinitialhecadecimalcodeline:
shellcode=(
Afterthat,removethefollowingline:
Unsignedcharbuf[]
Yourcodeinthenanotexteditorshouldappearlikethis:
![Page 87: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/87.jpg)
Scrolldownandfindthesemicolonlocatedneartheendofthescript.Addaclosingparenthesisbeforeit.Afterdoingso,addthefollowinglinesattheendofthecode:
Youshouldseethisonyourscreenafterdoingso:
Tosaveyourfile,pressCtrl+X,andthenpressYattheprompt.Entertoproceedsavingyourmodifiedfile.
CompiletheMalwareandRunItInordertorunthemodifiedmalware,youwillneedtocompileitfirst.Todothat,pullupa
![Page 88: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/88.jpg)
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.
![Page 89: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/89.jpg)
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.
![Page 90: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/90.jpg)
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:
![Page 91: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/91.jpg)
Whenyourunthiscodeinsidethetargetedmachineintheexample,youwillnoticethatthescripthasfoundtwousers,theAdministratorandalex.Youwillalsobeabletoseesomeofthefilesthatweredeletedthatyoumaywanttoretrieve:
![Page 92: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/92.jpg)
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.
![Page 93: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/93.jpg)
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!
![Page 94: Hacking with Python - webamooz.com · Introduction This book will show you how to use Python, create your own hacking tools ... combat new cracking programs that are developed every](https://reader031.vdocuments.site/reader031/viewer/2022021802/5b5bf1157f8b9a302a8ef3ec/html5/thumbnails/94.jpg)
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.