SanjibSinha
BeginningEthicalHackingwithPython
SanjibSinha
Howrah,WestBengal,India
Anysourcecodeorothersupplementarymaterialsreferencedbytheauthorin
thistextareavailabletoreadersatwww.apress.com.Fordetailed
informationabouthowtolocateyourbook’ssourcecode,goto
www.apress.com/source-code/.Readerscanalsoaccesssourcecode
atSpringerLinkintheSupplementaryMaterialsectionforeachchapter.
ISBN978-1-4842-2540-0
e-ISBN978-1-4842-2541-7
DOI10.1007/978-1-4842-2541-7
LibraryofCongressControlNumber:2016963222
©SanjibSinha2017
Thisworkissubjecttocopyright.AllrightsarereservedbythePublisher,
whetherthewholeorpartofthematerialisconcerned,specificallytherights
oftranslation,reprinting,reuseofillustrations,recitation,broadcasting,
reproductiononmicrofilmsorinanyotherphysicalway,andtransmissionor
informationstorageandretrieval,electronicadaptation,computersoftware,or
bysimilarordissimilarmethodologynowknownorhereafterdeveloped.
Trademarkednames,logos,andimagesmayappearinthisbook.Ratherthan
useatrademarksymbolwitheveryoccurrenceofatrademarkedname,logo,
orimageweusethenames,logos,andimagesonlyinaneditorialfashionand
tothebenefitofthetrademarkowner,withnointentionofinfringementofthe
trademark.Theuseinthispublicationoftradenames,trademarks,service
marks,andsimilarterms,eveniftheyarenotidentifiedassuch,isnottobe
takenasanexpressionofopinionastowhetherornottheyaresubjectto
proprietaryrights.
Whiletheadviceandinformationinthisbookarebelievedtobetrueand
accurateatthedateofpublication,neithertheauthorsnortheeditorsnorthe
publishercanacceptanylegalresponsibilityforanyerrorsoromissionsthat
maybemade.Thepublishermakesnowarranty,expressorimplied,with
respecttothematerialcontainedherein.
Printedonacid-freepaper
DistributedtothebooktradeworldwidebySpringerScience+BusinessMedia
NewYork,233SpringStreet,6thFloor,NewYork,NY10013.Phone1-800SPRINGER,fax(201)348-4505,e-mail,or
visitwww.springeronline.com.ApressMedia,LLCisaCaliforniaLLCandthe
solemember(owner)isSpringerScience+BusinessMediaFinanceInc
(SSBMFinanceInc).SSBMFinanceIncisaDelawarecorporation.
DR.AVIJITSEN,DRISTIPRADIP,KOLKATA.
(ForBringingLightintoDarkness)
Prologue–Hacker’sGoal
Thisbookisintendedforcompleteprogrammingbeginnersorgeneralpeople
whoknownothingaboutanyprogramminglanguagebutwanttolearnethical
hacking.
Letusclearitfirst:EthicalHackingisnotassociatedwithanykindof
illegalelectronicactivities.Theyalwaysstaywithinlaws.Thisbookis
intendedforthosepeople–youngandold–whoarecreativeandcuriousand
whowanttodevelopacreativehobbyortakeupinternetsecurityprofession
actingasethicalhacker.Keepingthatinmindwe’llalsolearnPython3
programminglanguagetoenhanceourskillasethicalhackers.
Thisbookisnotintendedforanykindofmalicioususer.Ifanyonetriesto
usethisbookoranytypeofcodeexamplesfromthisbookforillegalpurpose
thisbookwilltakenomoralresponsibilityforthatmaliciousbehaviours.
Ifyouthinkthatyoucanusethisbookforanymaliciouspurposethenyou
areadvisedtoreadthefirstchapter“LegalSideofEthicalHacking”.Ihope
youwon’tliketheideaofendingupinjailbyharmingsomeothersystems.
Iwouldliketostartthisbriefintroductionwithanimage.Thisimage
depictsmanythingsthatIwilllaterdiscussindetail.Itsays,“Theauthoris
using“Ubuntu”Linuxdistributionashisdefaultoperatingsystem.Hehas
installedVirtualBox–akindofvirtualmachine–thatrunsinWindowsalso.
AndinthatVirtualBoxhehasinstalledthreemoreoperatingsystems.Oneis
“WindowsXP”andtheothertwoare“KaliLinux”and“Windows7Ultimate”.
Theimagealsosays,andthatisveryimportant,“Currentlythreeoperating
systemsarevirtuallyrunningonthedesktop”.
(ThevirtualBoxisrunningthreeoperatingsystems.Youcantryany
kindofexperimentonthisVirtualOS.Thatwillnotdamageyourmain
system.)
Asanethicalhackeryouwilllearnhowtodefendyourself.Todefend
yourselfsometimeyouneedtoattackyourenemy.Butitisapartofyour
defensesystem.Itisapartofyourdefensestrategy.Moreyouknowaboutyour
enemy’sstrategy,moreyoucandefendyourself.Youneedtolearnthosetools
arefrequentlyusedbythemalicioushackersorcrackers.Theyusethesame
toolthatyouusetodefendyourself.
Whetheryouareanethicalhackeroramaliciouscracker,youdothesame
thing.Youusetheidenticalsoftwaretoolstoattackthesecuritysystem.Only
yourpurposeorintentiondiffers.
Probablyyouknowthatabigcarcompanybeforelaunchinganewmodel
ofcargenerallyteststhelockingsystem.Theyhavetheirownsecurity
engineersandbesidestheycallforthelockingexpertstotestthevulnerability.
Theypayagoodamountofmoneyifyoucanbreakthelockingsystemofthe
car.Basicallyitisaworkof“PENTESTING”.ThelockingexpertsPENTESTS
thesystemandseeifthereisanyweaknessinthesystem.
Itisgoodexampleofethicalhacking.Thelockingexpertsareinvitedtodo
thejobandtheyarepaidwell.Onthecontrarycarthievesdothesamejob
withoutanyinvitation.Theysimplybreakthelockingsystemofanunattended
carparkedontheroadsideandtakeitaway.Ihopebynowyouhave
understoodthedifferencebetweenethicalhackingandcracking.
Yourmainintentioncentersonthesecurityofthesystem.Securityconsists
offourkeycomponents.Asthebookprogressesyouwillincreasinglybe
findingwordslike“PENTESTING”,“EXPLOIT”,“PENETRATION”,
“BREAKINTHESYSTEM”,“COMPROMISETHEROUTER”etcetera.The
fourkeycomponentsmentionedbelowmainlydealwiththeseterms.Thekey
componentsare:
2. Integrity
3. Authenticity
4. Confidentiality
1. Availability
Wewillseehowcrackerswanttoattackthesecomponentstogainaccessto
thesystem.Sinceahacker ’smaingoalistoexploitthevulnerabilitiesofthe
systemsohewantstoseeifthereisanyweaknessinthesecorecomponents.
Letusassumethehackerwantstoblocktheavailabilityofthedata.Inthat
casehewillusethe“DenialofAttack”or‘DoS’method.Todothisattack
usuallyhackersusesystem’sresourceorbandwidth.ButDoShasmanyother
forms.Whentheresourceorbandwidthofyoursystemiseatenupcompletely,
theserverusuallycrashes.Thefinaltargetisonesystembutthenumberof
victimsisplenty.Itissomethinglikemillionsofpeoplegatherinfrontyour
housemaindoorandjamitwithakindofhumanchainsothatyouandyour
familymemberscannotenterintoit.
ThesecondkeycomponentIntegrityshouldnotbecompromisedatany
cost.Whatdoesthisterm“integrity”mean?It’sbasicallycenteredonthenature
ofdata.Whenthisnatureofdataistamperedwithsomekindof‘BITFLIPPING’attacks,theintegrityofthesystemisalsocompromised.Itcanbe
donejustbychangingthemessageitself.Thedatamayeitherbeinthemoveor
atrest,butitcanbechanged.Imaginewhathappenswhenatransactionof
moneyistamperedwiththeadditionoffewmorezeroesattheend!Letus
assumeabankistransferringmoney.Initsinstructionitiswritten:“transfer
$10,000”.Nowtheattackerchangesthecryptictextinsuchamannersothat
theamountchangesto$10,000000.Sotheattackisintendedforthemessage
itselforaseriesofmessages.
TheissueofauthenticationisnormallyhandledbytheMediaAccess
Control(MAC)filtering.Ifitisproperlyplacedthenetworkdoesnotallow
unauthorizeddevice.WhathappensifsomeonespoofstheMACAddressofa
legitimatenetworkstationandtakesitoff?Hecantakeonthestation’sidentity
andcontrolit.ThisiscalledauthenticationattackorMACAddressspoofing.
Finallytheissueofconfidentialityrisesaboveall.Datatravelincleartext
acrossthetrustednetwork.Heredatameaninformation.Theinformationtheft
likecrackingsomeone’spasswordisconfidentialityattack.Thedataor
informationisintendedforsomeonebutinsteadoftherecipientthehacker
gainstheaccess.Actuallythecrackerstealsitwhenthedataismovingacross
thetrustednetworkascleartext.
Acknowledgments
KARTICKPAUL,SYSTEMMANAGER,AAJKAAL,KOLKATA,Withouthis
persistentandinspiringhelp,Icouldnotwritethisbook.
Contents
PartI
Chapter1:LegalSideofHacking
Chapter2:HackingEnvironment
EthicalHackingandNetworking
WhatDoesNetworkMean?
Summary
Chapter3:InstallingVirtualBox
Chapter4:InstallingKaliLinuxandOtherOperatingSystemsonVB
Chapter5:LinuxTerminal,BasicCommands
Summary
PartII
Chapter6:Python3andEthicalHacking
Chapter7:PythonEnvironment
Chapter8:GeneralSyntaxes
Createthemain()function
IndentationandWhiteSpace
Commenting
AssigningValues
Chapter9:Variables,ObjectsandValues
UsingNumbers
String
WhatisTypeandID
LogicalValues
TuplesAndLists
Dictionary
Object
Chapter10:Conditionals
Chapter11:Loops
WhileLoops
ForLoops
Chapter12:RegularExpressions
Using“re”Module
ReusingWithRegularExpressions
SearchingwithRegularExpressions
Chapter13:Exceptions,CatchingErrors
Chapter14:Functions
ReturnValues
GenerateFunctions
ListsofArguments
NamedArguments
Chapter15:Classes
Object-OrientedMethodology
TheFoundationofObjectOrientation
UnderstandingClassesandObjects
WriteYourOwnGame,“GoodVsBad”
PrimaryClassandObject
AccessingObjectData
Polymorphism
UsingGenerators
Inheritance
Decorator
Chapter16:StringMethods
Chapter17:FileInputAndOutput
Chapter18:Containers
OperatingonTupleandListObject
OperatingonDictionaryObject
Chapter19:Database
LetusstartwithSQLite3
MySQLforBigProject
Chapter20:Module
Chapter21:Debugging,UnittestModule
Chapter22:SocketandNetworking
Chapter23:ImportingNmapModule
Chapter24:BuildinganNmapNetworkScanner
PartIII
Chapter25:ProtectAnonymityontheInternet
Chapter26:DarkWebandTor
HiddenWikipedia
Chapter27:ProxyChains
Chapter28:VirtualPrivateNetworkorVPN
Chapter29:MACAddress
Epilogue—WhatNext
Index
ContentsataGlance
AbouttheAuthor
AbouttheTechnicalReviewer
Acknowledgments
Prologue–Hacker ’sGoal
PartI
Chapter1:LegalSideofHacking
Chapter2:HackingEnvironment
Chapter3:InstallingVirtualBox
Chapter4:InstallingKaliLinuxandOtherOperatingSystemsonVB
Chapter5:LinuxTerminal,BasicCommands
PartII
Chapter6:Python3andEthicalHacking
Chapter7:PythonEnvironment
Chapter8:GeneralSyntaxes
Chapter9:Variables,ObjectsandValues
Chapter10:Conditionals
Chapter11:Loops
Chapter12:RegularExpressions
Chapter13:Exceptions,CatchingErrors
Chapter14:Functions
Chapter15:Classes
Chapter16:StringMethods
Chapter17:FileInputAndOutput
Chapter18:Containers
Chapter19:Database
Chapter20:Module
Chapter21:Debugging,UnittestModule
Chapter22:SocketandNetworking
Chapter23:ImportingNmapModule
Chapter24:BuildinganNmapNetworkScanner
PartIII
Chapter25:ProtectAnonymityontheInternet
Chapter26:DarkWebandTor
Chapter27:ProxyChains
Chapter28:VirtualPrivateNetworkorVPN
Chapter29:MACAddress
Epilogue—WhatNext
Index
AbouttheAuthorandAbouttheTechnical
Reviewer
AbouttheAuthor
SanjibSinha
writesstoriesandcodes—notalwaysinthesameorder.
HestartedwithC#and.NETframeworkandwonaMicrosoftCommunity
ContributorAwardin2011.Later,theOpenSourceSoftwaremovement
attractedhimandhebecameaLinux,PHP,andPythonenthusiast,specializing
inandworkingonWhiteHatEthicalHacking.
Asabeginner,hehadtostrugglealot—always—tofindoutaneasywayto
learncoding.Noonetoldhimthatcodingislikewriting:imagininganimage
andbringingitdowntoEarthwiththehelpofwordsandsymbols.
Allthroughhisbookshehastriedtohelpbeginnersfromtheirperspective
—asabeginner.
AbouttheTechnicalReviewer
AbirRanjanAtarthy
isaCertifiedEthicalHackerfromEc-Council,ISO27001AuditorandPCIDSS
implementer.
Hehasmorethan12yearsofextensivedomainexperienceindrivingthe
Information&CyberSecurityprogramsinallkeyaspectsi.e.Policy,
Standards,Procedures,Awareness,NetworkSecurity,Websecurity,Android
AppSecurity,IncidentResponse,SecurityAnalytics,SecurityMonitoring,
Malwareprotection,Securityconfiguration,Cryptography,DataProtection
Knowledgeofmostadvancedtoolsinsecurityindustrywithcomplementing
knowledgeonscriptinglanguagestomanuallyexploitvulnerabilities.
HehasauthoredseveraltechnicalarticleswhichhavebeenpublishedinIT
securityjournalsandisfrequentlyinvitedtospeakatmanycybersecurity
conferencesandPythonforums.
HehasdesignedcybersecuritycoursesforCorporatesonnetworkandweb
penetrationtesting,forensics,andcryptography.
Abirregularlyconductswork-shops,trainingsessionsandcertification
programsforcorporates,governmentorganizations,defenceestablishments,
securityagencies,engineeringcollegesanduniversitiesonPython
programming,penetrationtestingandcyberforensics.
HehascreatedseveralITsecurityandcryptographictoolsusingPython.
HehasaccomplishedshorttermProgramsinObject-oriented
programmingandSelectedTopicsinSoftwareEngineeringfromIndian
InstituteofTechnology-Kharagpur.
Abirisconsideredasubject-matterexpertincybersecurityandisoften
quotedbyleadingnewspapersandTVchannels.
PresentlyheisleadingtheCyberthreatintelligencedepartmentinTCG
DigitalSolutionsPvt.Ltd.
PartI
©SanjibSinha2017
SanjibSinha,BeginningEthicalHackingwithPython,DOI10.1007/978-1-4842-254 1-7_1
1.LegalSideofHacking
SanjibSinha1
(1) Howrah,WestBengal,India
Electronicsupplementarymaterial
Theonlineversionofthischapter(doi:10.1007/9 78-1-4842-2541-7_1)
containssupplementarymaterial,whichisavailabletoauthorizedusers.
Astimegoesbyandweprogress,ouroldenvironmentisalsochangingvery
fast.Ithasnotbeenlikebeforewhenwekeeprecordsbyenteringdataintoa
biglogbookandstackthemonebyonedate-wise.Nowwekeepdataina
computer.Wedon’tgotoamarketanymoretobuyanything.Weorderitover
theInternetandpaymentismadebyusingcreditordebitcard.Thenatureof
crimehasalsochangedaccordingly.
Criminalsusedtosnatchyourdataphysicallybefore.Theynowsnatchit
overtheInternetusingcomputers.Nowcomputershavebecomeanewtoolfor
businessaswellasfortraditionalcrimes.Onthebasisofwhich,aterm
—“cyberlaw”—comestothefore.Asanethicalhacker,thefirstandmost
basicthingyoushouldrememberis“don’ttrytopenetrateortamperanyother
systemwithoutaskingpermission.”
YoumayaskhowIwouldexperimentwithmyknowledge.Theansweris
VirtualBox.Inyourvirtualmachineyoumayinstallasmanyoperating
systemsasyouwantandexperimentonthem(TheaboveimagedepictsVirtual
Boxandtwooperatingsystemsrunninginit).Tryeverythingonthem.Trying
anyvirusonyourvirtualmachinewillnotaffectyourmainsystem.Atthe
sametimeyouwillkeeplearningaboutmalware,virusesandeverykindof
possibleattack.
Afewexamplesmaygiveyouanideawhattypeofcomputercrimesare
punishableinourlegalsystem.
Ifyouuseanysoftwaretooltogenerateacreditcardordebitcardnumber,
thenitisahighlypunishableoffense.Itwillinviteafineoffiftythousand
dollarsandfifteenyearsofimprisonment.Settingupaboguswebsitetotake
creditcardnumberswithafalsepromiseofsellingnon-existentproductsisa
highlypunishableoffense.Rigorousimprisonmentandaheftyfinefollow.I
cangiveyouseveralotherexamplesthatmayinvitetroubleforyouifyou
don’tstaywithinthelaw.
Remember,youareanethicalhackerandyouarelearninghackingtools
forprotectingyouroryourclient’ssystem.Forthesakeofprotectionand
defense,youneedtoknowtheattack,exploitorpenetrationmethods.
Tryeverysingleexperimentonyourvirtualmachine.
Thatistherulenumberoneofethicalhacking.
©SanjibSinha2017
SanjibSinha,BeginningEthicalHackingwithPython,DOI10.1007/978-1-4842-254 1-7_2
2.HackingEnvironment
SanjibSinha1
(1) Howrah,WestBengal,India
Theveryfirstthingthatyouneedisavirtualmachine.AsIsaidbefore,Ihave
UbuntuasmydefaultoperatingsystemandinsidemyvirtualmachineIhave
installedtwooperatingsystems—oneisWindowsXPandtheotherisKali
Linux.
Technically,fromnowonIwouldmentionWindowsXPandKaliLinuxas
myvirtualmachines.KaliLinuxisaLinuxdistributionthatcomesupwith
manyusefulhackingtools.SoIstronglysuggestusingitasyourvirtual
machine.YoumayalsoreadthedocumentationpageofKaliLinux,whichwill
alsobeanimmensehelp.
Atthesametime,I’dnotsuggestusingWindowsofanykindfortheethical
hackingpurpose.Somemayarguethatfewhackingtoolscanbeusedin
Windows,sowhyyouaresuggestingotherwise?Thepointis:intheethical
hackingworld,youneedtobeanonymousallthetime.Youwon’twanttokeep
yourtrail,anyway,sothatyoucanbetracedback.Remaininganonymousisa
bigchallenge.InLinuxitisfairlyeasyandyoucanstayanonymousforthe
timebeing.
Keepingthatinmind,Iexplainthattechniqueofbeinganonymousingreat
detailsothatbeforejumpingupintothebigtask,youmakeyourdefensemuch
stronger.Beinganonymousisthemostimportantthingintheworldofethical
hacking.KeepingyourselfanonymousinWindowsisnotpossible.Soitis
bettertoadapttotheLinuxenvironmentfirst.Anotherimportantthingis,most
ofthegreathackingtoolsarenotavailableintheWindowsenvironment.
IfyouhaveneverheardofanyLinuxdistribution,don’tworry.Youcan
eitherinstalluser-friendlyUbuntuinsideyourWindowssystemoryoucan
easilypartitionyourdiskintotwopartsandinstallUbuntuandWindows
separatelyasyourtwodefaultoperatingsystems.Itispreferabletodothe
latter.Installinganduninstallingparalleloperatingsystemsalwaysteachesyou
somethingnew.IfyouarefamiliarwithWindows,Iwon’ttellyoutosimply
dumpitforthesakeoflearningethicalhacking.Youcankeepitanduseitfor
yourdailywork.Thereisnoproblemindoingthis.
IntheInternetworld,Linuxisusedmore.SoyouneedtolearnafewLinux
commands.SoftwareinstallationinLinuxisslightlydifferentfromWindows
environments.ThereareLinuxdistributionslikeFedoraorDebian,andmany
more.InamedUbuntujustbecauseitisextremelypopularandWindowsusers
findthemselvescomfortableinsideit.Theoperationsaremoreorlessthe
same,includingthesoftwareinstallations.Forbeginners,itisnotagoodidea
toinstallKaliLinuxasyourdefaultOS.YoumustreadKalidocumentation,
whereitisclearlystatedthatKaliismorefordevelopers.Youaregoingto
installitinsideyourVirtualBox.KaliLinuxisakindofLinuxdistributionthat
comeswithlotofhackingtools.Youneedtoknowthemandusetheminthe
courseofethicalhacking.
InstallingVirtualMachineisaveryimportantstepasthefirststepof
buildingyourenvironment.InthenextchapterIwillshowyouhowyoucando
thatfordifferentoperatingsystems.Anotherimportantthingislearninga
programminglanguagethatwillreallyhelpyoulearnethicalhackingbetter.
TheobviouschoiceisPython.Atthetimeofwritingthisbook,Python3.x
hasalreadyarrivedandisconsideredthefutureofthislanguage.Itisvery
quicklycatchingupwiththeoldPython2.xversion,whichhasbeenaroundthe
marketforawhile.TheofficialPythondownloadpageprovidestherepository
ofPythoninstallersforWindows,MacOSXandLinuxoperatingsystems.If
youdownloadaninstaller,itisofimmensehelpbecauseitcomeswiththe
Pythoninterpreter,standardlibrary,andstandardmodules.Thestandard
libraryandbuilt-inmodulesarespecificallyveryimportantbecausetheyoffer
youseveralusefulcapabilitiesthatwillhelpyouachieveyourgoalasan
ethicalhacker.Amongtheusefulmodules,youwillgetcryptographicservices,
Internetdatahandling,interactionwithIPprotocols,interoperabilitywiththe
operatingsystem,andmanymore.Sogoahead,pickupanygoodbeginner ’s
bookonPython,readtheofficialdocumentationandknowthatitisapartof
yourlearningschedule.Pythonisanextremelyeasylanguagetolearn.
Tocreateanidealethicalhacker ’senvironment,afewstepsareextremely
important.Thestepsinclude:installingVirtualMachineorVirtualBox(VB),
havingabasicknowledgeaboutnetworking,andlearningauseful
programminglanguagelikePython.Letusfirsthavealookatthebasic
networkingknowledge.