iot security applied on a smart door lock application1216681/fulltext01.pdfing a smart door lock for...

56
INOM EXAMENSARBETE TEKNIK, GRUNDNIVÅ, 15 HP , STOCKHOLM SVERIGE 2018 IoT Security Applied on a Smart Door Lock Application KRISTOFFER DJUPSJÖ MASAR ALMOSAWI KTH SKOLAN FÖR ELEKTROTEKNIK OCH DATAVETENSKAP

Upload: others

Post on 09-Mar-2021

3 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

INOM EXAMENSARBETE TEKNIKGRUNDNIVAring 15 HP

STOCKHOLM SVERIGE 2018

IoT Security Applied on a Smart Door Lock Application

KRISTOFFER DJUPSJOuml

MASAR ALMOSAWI

KTHSKOLAN FOumlR ELEKTROTEKNIK OCH DATAVETENSKAP

2

Abstract

This thesis describes the development of an IOT application based upon Digitiz-ing a smart door lock for making it connected to the internet and able to recognizeemployees that work in the office

This thesis concentrates primarily on the security aspects by listing the typicalsecurity challenges in IOT systems in general and summing these challenges up todevelop a functional and secure product from scratch A microcontroller is chosen forthis project and a test environment is built to experiment and develop the securitybreaches Architectural designs are chosen for the API being developed and even forthe Android Application A detailed description is made of the multi-master databaserepresented by Azure active directory and its importance to achieving the security ofan essential security breach A new technique called Eddystone is introduced in theproject to serve the transmission protocol with Bluetooth beacons

The final stage of this project is completing the development of the Android appli-cation and making sure that all the subsystems developed do communicate with eachother to deliver a functional and secure flow of the IoT system

3

4

Sammanfattning

Foumlljande examensarbete beskriver utvecklingen av en IoT-produkt baserad paring dig-italisering av ett smart doumlrrlarings daumlr applikationen ansluts till internet foumlr igenkaumlnningav anstaumlllda som arbetar paring ett kontor Examensarbetet fokuserar primaumlrt paring saumlk-erhetsaspekterna genom att notera de typiska saumlkerhetsutmaningarna som generellaIOT-system utsaumltts foumlr och summerar dessa utmaningar foumlr att utveckla en funktionelloch saumlker produkt fraringn start av projektet

En mikrokontroller vaumlljs ut specifikt foumlr projektet och en testmiljouml byggs foumlr attundersoumlka och motverka eventuella saumlkerhetsbrister

Rapporten ger aumlven detaljerad beskrivning av multi-master databasen Azure Ac-tive Directory och dess betydelse foumlr att uppnaring oumlnskad saumlkerheten i systemet Enny teknik som heter Eddystone introduceras i projektet foumlr att betjaumlna som oumlver-foumlringsprotokoll till Bluetooth-beacons

Det sista steget i detta projekt kompletteras utvecklingen av systemet med Android-applikation som ser till att alla utvecklade delsystem kommunicerar med varandra ochlevererar ett funktionellt och saumlkert floumlde av IOT-systemet

5

6

Contents

1 Introduction 1311 Background 1312 Problem Definition 1313 Purpose 1314 Goals 1415 Research Methodology 1416 Delimitation 1417 Structure of Thesis 14

2 Background 1521 Internet of Things 15

211 IoT Architecture 15212 Foundation Of physical environment in IoT 15213 Basic Structure of Typical IoT Application 16

22 Consumer Internet Of Things 1623 Understanding IoT Security 1624 Security Challenges In IoT Systems 17

241 LAN Mistrust 17242 Environment Mistrust 17243 Application over-privilege 18244 NoWeak Authentication 18245 Implementation Flaws 18

25 Security Solution For IoT Systems 18251 LAN Mistrust 18252 Environment Mistrust 19253 Application Over-Privilege 19254 No Weak Authentication 19255 Implementation Flaws 19

26 The Smart Door Lock 19261 Direct Internet Connection 20262 Automatic Door Unlocking 20263 Other products on the market 21

27 Hardware Review 22271 Microcontroller Unit 22272 Bluetooth Transmitter (Beacons) 22273 Smartphone 22

28 The Software Representation 2229 Computing Concepts 22

291 Cloud Computing Models 22

3 Methodology 2531 Pilot Study 2532 Design Of Prototype 2533 Implementation of the Design 2534 Test Plan 26

7

4 Setting Up A Test environment 2741 Choice of Microcontroller Unit 2742 Choice of Bluetooth Beacons 2743 Test EnvironmentExperimental Design 27

431 Controlling a Door Circuit using a Relay 27432 Test of MCU 27433 Schematic of the electronic door lock 28

5 System Structure 2951 Using Beacons to Monitor User Location 30

511 What is Eddystone 3052 What is REST API 3053 Communicating to and from the REST API 3154 What Is an Active directory 31

541 Using Azure Active Directory to Authenticate Users 31542 What is an Access Token and why do we need it 31

6 Software Development 3361 Android Test Application to connect Google Beacon and Particle Device 33

611 Receiving A String from Beacon to App 33612 Sending A Request from App to Particle 34613 Particle Console IDE 35

62 Creating a Azure AD tenant and Developing Authentication API 35621 Creating A Suitable Test Environment for WebAPI 36622 Creating A Tenant And Users in Azure AD 36623 Authentication API Development 37624 Test Retrieve a token 38

63 Door API Development 38631 Security of API 39632 Connecting to Particle 39633 Test HTTPS from Postman 40

64 Android DevelopmentArchitecture 40641 Using Android framework Components in SDL Application 41642 Application Overview 41643 Integration of Google Beacons 42644 Permissions and requirements 43

7 Result and Analysis 4571 Primary Results 4572 Discussion 47

721 LAN misstrust 47722 Environment misstrust 47723 Application over-privilege 48724 NoWeak Authentication 49725 Implementation Flaws 49

8 Conclusion and Future Work 5181 Conclusion 5182 Ethics Sustainability and Benefits 5183 Risks 5284 Future Work 52

8

List of Figures

1 Infrastructure of Iot ecosystem 162 Naive architecture of the Smart Door Lock 203 Example of house layout where a Bluetooth direction sense algorithm fails

to detect whether the user is inside the building or not 214 Schematic of the working relay The lock is represented as a LED in the

experimental design 285 System Architecture with a base flow of the system and security leakages 296 Communication between android app and Google APIs 347 Basic flow for sending request from Android to particle 358 Retrieving an access token using HTTP request in form of JSON 389 HTTPS request and response from Particle Device 3910 Android Layers 4011 Android App interaction 4212 Message Exchange Using Google Nearby 4313 Current test members of the Active Directory 4514 Request traffic to Google APIs where Nearby API is blue and Proximity

API is green 4515 The APIrsquos request- and error rate 4516 User login UI 4617 Login Successful UI 4618 Particle Spark Console displaying various events relative to the specific Pho-

ton Device 46

9

10

Acronyms

IoT Internet of Things

SDL Smart Door Lock

API Application Programming Interface

DGC Device-Gateway-Cloud

DIC Direct-Internet-Connection

RESTful Representational State Transfer

IT Information Technology

WLAN Wireless Local Area Network

DoS Denial of Service

PIN Postal Index Number

XSS Cross-Site Scripting

MAC Media Access Control

MCU Microcontroller Unit

OS Operating System

SaaS Software as a Service

PaaS Platform as a Service

IaaS Infrastructure as a Service

IO InputOutput

SDK Software Development Kit

HTTP Hypertext Transfer Protocol

HTTPS HTTP over SSL

SSL Secure Socket Layer

LED Light-Emitting Diode

AAD Azure Active Directory

EID Ephemeral Identifier

UID Unique Identifier

URL Uniform Resource Locator

BLE Bluetooth Low Energy

XML Extensible Markup Language

JSON JavaScript Object Notation

11

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 2: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

2

Abstract

This thesis describes the development of an IOT application based upon Digitiz-ing a smart door lock for making it connected to the internet and able to recognizeemployees that work in the office

This thesis concentrates primarily on the security aspects by listing the typicalsecurity challenges in IOT systems in general and summing these challenges up todevelop a functional and secure product from scratch A microcontroller is chosen forthis project and a test environment is built to experiment and develop the securitybreaches Architectural designs are chosen for the API being developed and even forthe Android Application A detailed description is made of the multi-master databaserepresented by Azure active directory and its importance to achieving the security ofan essential security breach A new technique called Eddystone is introduced in theproject to serve the transmission protocol with Bluetooth beacons

The final stage of this project is completing the development of the Android appli-cation and making sure that all the subsystems developed do communicate with eachother to deliver a functional and secure flow of the IoT system

3

4

Sammanfattning

Foumlljande examensarbete beskriver utvecklingen av en IoT-produkt baserad paring dig-italisering av ett smart doumlrrlarings daumlr applikationen ansluts till internet foumlr igenkaumlnningav anstaumlllda som arbetar paring ett kontor Examensarbetet fokuserar primaumlrt paring saumlk-erhetsaspekterna genom att notera de typiska saumlkerhetsutmaningarna som generellaIOT-system utsaumltts foumlr och summerar dessa utmaningar foumlr att utveckla en funktionelloch saumlker produkt fraringn start av projektet

En mikrokontroller vaumlljs ut specifikt foumlr projektet och en testmiljouml byggs foumlr attundersoumlka och motverka eventuella saumlkerhetsbrister

Rapporten ger aumlven detaljerad beskrivning av multi-master databasen Azure Ac-tive Directory och dess betydelse foumlr att uppnaring oumlnskad saumlkerheten i systemet Enny teknik som heter Eddystone introduceras i projektet foumlr att betjaumlna som oumlver-foumlringsprotokoll till Bluetooth-beacons

Det sista steget i detta projekt kompletteras utvecklingen av systemet med Android-applikation som ser till att alla utvecklade delsystem kommunicerar med varandra ochlevererar ett funktionellt och saumlkert floumlde av IOT-systemet

5

6

Contents

1 Introduction 1311 Background 1312 Problem Definition 1313 Purpose 1314 Goals 1415 Research Methodology 1416 Delimitation 1417 Structure of Thesis 14

2 Background 1521 Internet of Things 15

211 IoT Architecture 15212 Foundation Of physical environment in IoT 15213 Basic Structure of Typical IoT Application 16

22 Consumer Internet Of Things 1623 Understanding IoT Security 1624 Security Challenges In IoT Systems 17

241 LAN Mistrust 17242 Environment Mistrust 17243 Application over-privilege 18244 NoWeak Authentication 18245 Implementation Flaws 18

25 Security Solution For IoT Systems 18251 LAN Mistrust 18252 Environment Mistrust 19253 Application Over-Privilege 19254 No Weak Authentication 19255 Implementation Flaws 19

26 The Smart Door Lock 19261 Direct Internet Connection 20262 Automatic Door Unlocking 20263 Other products on the market 21

27 Hardware Review 22271 Microcontroller Unit 22272 Bluetooth Transmitter (Beacons) 22273 Smartphone 22

28 The Software Representation 2229 Computing Concepts 22

291 Cloud Computing Models 22

3 Methodology 2531 Pilot Study 2532 Design Of Prototype 2533 Implementation of the Design 2534 Test Plan 26

7

4 Setting Up A Test environment 2741 Choice of Microcontroller Unit 2742 Choice of Bluetooth Beacons 2743 Test EnvironmentExperimental Design 27

431 Controlling a Door Circuit using a Relay 27432 Test of MCU 27433 Schematic of the electronic door lock 28

5 System Structure 2951 Using Beacons to Monitor User Location 30

511 What is Eddystone 3052 What is REST API 3053 Communicating to and from the REST API 3154 What Is an Active directory 31

541 Using Azure Active Directory to Authenticate Users 31542 What is an Access Token and why do we need it 31

6 Software Development 3361 Android Test Application to connect Google Beacon and Particle Device 33

611 Receiving A String from Beacon to App 33612 Sending A Request from App to Particle 34613 Particle Console IDE 35

62 Creating a Azure AD tenant and Developing Authentication API 35621 Creating A Suitable Test Environment for WebAPI 36622 Creating A Tenant And Users in Azure AD 36623 Authentication API Development 37624 Test Retrieve a token 38

63 Door API Development 38631 Security of API 39632 Connecting to Particle 39633 Test HTTPS from Postman 40

64 Android DevelopmentArchitecture 40641 Using Android framework Components in SDL Application 41642 Application Overview 41643 Integration of Google Beacons 42644 Permissions and requirements 43

7 Result and Analysis 4571 Primary Results 4572 Discussion 47

721 LAN misstrust 47722 Environment misstrust 47723 Application over-privilege 48724 NoWeak Authentication 49725 Implementation Flaws 49

8 Conclusion and Future Work 5181 Conclusion 5182 Ethics Sustainability and Benefits 5183 Risks 5284 Future Work 52

8

List of Figures

1 Infrastructure of Iot ecosystem 162 Naive architecture of the Smart Door Lock 203 Example of house layout where a Bluetooth direction sense algorithm fails

to detect whether the user is inside the building or not 214 Schematic of the working relay The lock is represented as a LED in the

experimental design 285 System Architecture with a base flow of the system and security leakages 296 Communication between android app and Google APIs 347 Basic flow for sending request from Android to particle 358 Retrieving an access token using HTTP request in form of JSON 389 HTTPS request and response from Particle Device 3910 Android Layers 4011 Android App interaction 4212 Message Exchange Using Google Nearby 4313 Current test members of the Active Directory 4514 Request traffic to Google APIs where Nearby API is blue and Proximity

API is green 4515 The APIrsquos request- and error rate 4516 User login UI 4617 Login Successful UI 4618 Particle Spark Console displaying various events relative to the specific Pho-

ton Device 46

9

10

Acronyms

IoT Internet of Things

SDL Smart Door Lock

API Application Programming Interface

DGC Device-Gateway-Cloud

DIC Direct-Internet-Connection

RESTful Representational State Transfer

IT Information Technology

WLAN Wireless Local Area Network

DoS Denial of Service

PIN Postal Index Number

XSS Cross-Site Scripting

MAC Media Access Control

MCU Microcontroller Unit

OS Operating System

SaaS Software as a Service

PaaS Platform as a Service

IaaS Infrastructure as a Service

IO InputOutput

SDK Software Development Kit

HTTP Hypertext Transfer Protocol

HTTPS HTTP over SSL

SSL Secure Socket Layer

LED Light-Emitting Diode

AAD Azure Active Directory

EID Ephemeral Identifier

UID Unique Identifier

URL Uniform Resource Locator

BLE Bluetooth Low Energy

XML Extensible Markup Language

JSON JavaScript Object Notation

11

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 3: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

Abstract

This thesis describes the development of an IOT application based upon Digitiz-ing a smart door lock for making it connected to the internet and able to recognizeemployees that work in the office

This thesis concentrates primarily on the security aspects by listing the typicalsecurity challenges in IOT systems in general and summing these challenges up todevelop a functional and secure product from scratch A microcontroller is chosen forthis project and a test environment is built to experiment and develop the securitybreaches Architectural designs are chosen for the API being developed and even forthe Android Application A detailed description is made of the multi-master databaserepresented by Azure active directory and its importance to achieving the security ofan essential security breach A new technique called Eddystone is introduced in theproject to serve the transmission protocol with Bluetooth beacons

The final stage of this project is completing the development of the Android appli-cation and making sure that all the subsystems developed do communicate with eachother to deliver a functional and secure flow of the IoT system

3

4

Sammanfattning

Foumlljande examensarbete beskriver utvecklingen av en IoT-produkt baserad paring dig-italisering av ett smart doumlrrlarings daumlr applikationen ansluts till internet foumlr igenkaumlnningav anstaumlllda som arbetar paring ett kontor Examensarbetet fokuserar primaumlrt paring saumlk-erhetsaspekterna genom att notera de typiska saumlkerhetsutmaningarna som generellaIOT-system utsaumltts foumlr och summerar dessa utmaningar foumlr att utveckla en funktionelloch saumlker produkt fraringn start av projektet

En mikrokontroller vaumlljs ut specifikt foumlr projektet och en testmiljouml byggs foumlr attundersoumlka och motverka eventuella saumlkerhetsbrister

Rapporten ger aumlven detaljerad beskrivning av multi-master databasen Azure Ac-tive Directory och dess betydelse foumlr att uppnaring oumlnskad saumlkerheten i systemet Enny teknik som heter Eddystone introduceras i projektet foumlr att betjaumlna som oumlver-foumlringsprotokoll till Bluetooth-beacons

Det sista steget i detta projekt kompletteras utvecklingen av systemet med Android-applikation som ser till att alla utvecklade delsystem kommunicerar med varandra ochlevererar ett funktionellt och saumlkert floumlde av IOT-systemet

5

6

Contents

1 Introduction 1311 Background 1312 Problem Definition 1313 Purpose 1314 Goals 1415 Research Methodology 1416 Delimitation 1417 Structure of Thesis 14

2 Background 1521 Internet of Things 15

211 IoT Architecture 15212 Foundation Of physical environment in IoT 15213 Basic Structure of Typical IoT Application 16

22 Consumer Internet Of Things 1623 Understanding IoT Security 1624 Security Challenges In IoT Systems 17

241 LAN Mistrust 17242 Environment Mistrust 17243 Application over-privilege 18244 NoWeak Authentication 18245 Implementation Flaws 18

25 Security Solution For IoT Systems 18251 LAN Mistrust 18252 Environment Mistrust 19253 Application Over-Privilege 19254 No Weak Authentication 19255 Implementation Flaws 19

26 The Smart Door Lock 19261 Direct Internet Connection 20262 Automatic Door Unlocking 20263 Other products on the market 21

27 Hardware Review 22271 Microcontroller Unit 22272 Bluetooth Transmitter (Beacons) 22273 Smartphone 22

28 The Software Representation 2229 Computing Concepts 22

291 Cloud Computing Models 22

3 Methodology 2531 Pilot Study 2532 Design Of Prototype 2533 Implementation of the Design 2534 Test Plan 26

7

4 Setting Up A Test environment 2741 Choice of Microcontroller Unit 2742 Choice of Bluetooth Beacons 2743 Test EnvironmentExperimental Design 27

431 Controlling a Door Circuit using a Relay 27432 Test of MCU 27433 Schematic of the electronic door lock 28

5 System Structure 2951 Using Beacons to Monitor User Location 30

511 What is Eddystone 3052 What is REST API 3053 Communicating to and from the REST API 3154 What Is an Active directory 31

541 Using Azure Active Directory to Authenticate Users 31542 What is an Access Token and why do we need it 31

6 Software Development 3361 Android Test Application to connect Google Beacon and Particle Device 33

611 Receiving A String from Beacon to App 33612 Sending A Request from App to Particle 34613 Particle Console IDE 35

62 Creating a Azure AD tenant and Developing Authentication API 35621 Creating A Suitable Test Environment for WebAPI 36622 Creating A Tenant And Users in Azure AD 36623 Authentication API Development 37624 Test Retrieve a token 38

63 Door API Development 38631 Security of API 39632 Connecting to Particle 39633 Test HTTPS from Postman 40

64 Android DevelopmentArchitecture 40641 Using Android framework Components in SDL Application 41642 Application Overview 41643 Integration of Google Beacons 42644 Permissions and requirements 43

7 Result and Analysis 4571 Primary Results 4572 Discussion 47

721 LAN misstrust 47722 Environment misstrust 47723 Application over-privilege 48724 NoWeak Authentication 49725 Implementation Flaws 49

8 Conclusion and Future Work 5181 Conclusion 5182 Ethics Sustainability and Benefits 5183 Risks 5284 Future Work 52

8

List of Figures

1 Infrastructure of Iot ecosystem 162 Naive architecture of the Smart Door Lock 203 Example of house layout where a Bluetooth direction sense algorithm fails

to detect whether the user is inside the building or not 214 Schematic of the working relay The lock is represented as a LED in the

experimental design 285 System Architecture with a base flow of the system and security leakages 296 Communication between android app and Google APIs 347 Basic flow for sending request from Android to particle 358 Retrieving an access token using HTTP request in form of JSON 389 HTTPS request and response from Particle Device 3910 Android Layers 4011 Android App interaction 4212 Message Exchange Using Google Nearby 4313 Current test members of the Active Directory 4514 Request traffic to Google APIs where Nearby API is blue and Proximity

API is green 4515 The APIrsquos request- and error rate 4516 User login UI 4617 Login Successful UI 4618 Particle Spark Console displaying various events relative to the specific Pho-

ton Device 46

9

10

Acronyms

IoT Internet of Things

SDL Smart Door Lock

API Application Programming Interface

DGC Device-Gateway-Cloud

DIC Direct-Internet-Connection

RESTful Representational State Transfer

IT Information Technology

WLAN Wireless Local Area Network

DoS Denial of Service

PIN Postal Index Number

XSS Cross-Site Scripting

MAC Media Access Control

MCU Microcontroller Unit

OS Operating System

SaaS Software as a Service

PaaS Platform as a Service

IaaS Infrastructure as a Service

IO InputOutput

SDK Software Development Kit

HTTP Hypertext Transfer Protocol

HTTPS HTTP over SSL

SSL Secure Socket Layer

LED Light-Emitting Diode

AAD Azure Active Directory

EID Ephemeral Identifier

UID Unique Identifier

URL Uniform Resource Locator

BLE Bluetooth Low Energy

XML Extensible Markup Language

JSON JavaScript Object Notation

11

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 4: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

4

Sammanfattning

Foumlljande examensarbete beskriver utvecklingen av en IoT-produkt baserad paring dig-italisering av ett smart doumlrrlarings daumlr applikationen ansluts till internet foumlr igenkaumlnningav anstaumlllda som arbetar paring ett kontor Examensarbetet fokuserar primaumlrt paring saumlk-erhetsaspekterna genom att notera de typiska saumlkerhetsutmaningarna som generellaIOT-system utsaumltts foumlr och summerar dessa utmaningar foumlr att utveckla en funktionelloch saumlker produkt fraringn start av projektet

En mikrokontroller vaumlljs ut specifikt foumlr projektet och en testmiljouml byggs foumlr attundersoumlka och motverka eventuella saumlkerhetsbrister

Rapporten ger aumlven detaljerad beskrivning av multi-master databasen Azure Ac-tive Directory och dess betydelse foumlr att uppnaring oumlnskad saumlkerheten i systemet Enny teknik som heter Eddystone introduceras i projektet foumlr att betjaumlna som oumlver-foumlringsprotokoll till Bluetooth-beacons

Det sista steget i detta projekt kompletteras utvecklingen av systemet med Android-applikation som ser till att alla utvecklade delsystem kommunicerar med varandra ochlevererar ett funktionellt och saumlkert floumlde av IOT-systemet

5

6

Contents

1 Introduction 1311 Background 1312 Problem Definition 1313 Purpose 1314 Goals 1415 Research Methodology 1416 Delimitation 1417 Structure of Thesis 14

2 Background 1521 Internet of Things 15

211 IoT Architecture 15212 Foundation Of physical environment in IoT 15213 Basic Structure of Typical IoT Application 16

22 Consumer Internet Of Things 1623 Understanding IoT Security 1624 Security Challenges In IoT Systems 17

241 LAN Mistrust 17242 Environment Mistrust 17243 Application over-privilege 18244 NoWeak Authentication 18245 Implementation Flaws 18

25 Security Solution For IoT Systems 18251 LAN Mistrust 18252 Environment Mistrust 19253 Application Over-Privilege 19254 No Weak Authentication 19255 Implementation Flaws 19

26 The Smart Door Lock 19261 Direct Internet Connection 20262 Automatic Door Unlocking 20263 Other products on the market 21

27 Hardware Review 22271 Microcontroller Unit 22272 Bluetooth Transmitter (Beacons) 22273 Smartphone 22

28 The Software Representation 2229 Computing Concepts 22

291 Cloud Computing Models 22

3 Methodology 2531 Pilot Study 2532 Design Of Prototype 2533 Implementation of the Design 2534 Test Plan 26

7

4 Setting Up A Test environment 2741 Choice of Microcontroller Unit 2742 Choice of Bluetooth Beacons 2743 Test EnvironmentExperimental Design 27

431 Controlling a Door Circuit using a Relay 27432 Test of MCU 27433 Schematic of the electronic door lock 28

5 System Structure 2951 Using Beacons to Monitor User Location 30

511 What is Eddystone 3052 What is REST API 3053 Communicating to and from the REST API 3154 What Is an Active directory 31

541 Using Azure Active Directory to Authenticate Users 31542 What is an Access Token and why do we need it 31

6 Software Development 3361 Android Test Application to connect Google Beacon and Particle Device 33

611 Receiving A String from Beacon to App 33612 Sending A Request from App to Particle 34613 Particle Console IDE 35

62 Creating a Azure AD tenant and Developing Authentication API 35621 Creating A Suitable Test Environment for WebAPI 36622 Creating A Tenant And Users in Azure AD 36623 Authentication API Development 37624 Test Retrieve a token 38

63 Door API Development 38631 Security of API 39632 Connecting to Particle 39633 Test HTTPS from Postman 40

64 Android DevelopmentArchitecture 40641 Using Android framework Components in SDL Application 41642 Application Overview 41643 Integration of Google Beacons 42644 Permissions and requirements 43

7 Result and Analysis 4571 Primary Results 4572 Discussion 47

721 LAN misstrust 47722 Environment misstrust 47723 Application over-privilege 48724 NoWeak Authentication 49725 Implementation Flaws 49

8 Conclusion and Future Work 5181 Conclusion 5182 Ethics Sustainability and Benefits 5183 Risks 5284 Future Work 52

8

List of Figures

1 Infrastructure of Iot ecosystem 162 Naive architecture of the Smart Door Lock 203 Example of house layout where a Bluetooth direction sense algorithm fails

to detect whether the user is inside the building or not 214 Schematic of the working relay The lock is represented as a LED in the

experimental design 285 System Architecture with a base flow of the system and security leakages 296 Communication between android app and Google APIs 347 Basic flow for sending request from Android to particle 358 Retrieving an access token using HTTP request in form of JSON 389 HTTPS request and response from Particle Device 3910 Android Layers 4011 Android App interaction 4212 Message Exchange Using Google Nearby 4313 Current test members of the Active Directory 4514 Request traffic to Google APIs where Nearby API is blue and Proximity

API is green 4515 The APIrsquos request- and error rate 4516 User login UI 4617 Login Successful UI 4618 Particle Spark Console displaying various events relative to the specific Pho-

ton Device 46

9

10

Acronyms

IoT Internet of Things

SDL Smart Door Lock

API Application Programming Interface

DGC Device-Gateway-Cloud

DIC Direct-Internet-Connection

RESTful Representational State Transfer

IT Information Technology

WLAN Wireless Local Area Network

DoS Denial of Service

PIN Postal Index Number

XSS Cross-Site Scripting

MAC Media Access Control

MCU Microcontroller Unit

OS Operating System

SaaS Software as a Service

PaaS Platform as a Service

IaaS Infrastructure as a Service

IO InputOutput

SDK Software Development Kit

HTTP Hypertext Transfer Protocol

HTTPS HTTP over SSL

SSL Secure Socket Layer

LED Light-Emitting Diode

AAD Azure Active Directory

EID Ephemeral Identifier

UID Unique Identifier

URL Uniform Resource Locator

BLE Bluetooth Low Energy

XML Extensible Markup Language

JSON JavaScript Object Notation

11

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 5: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

Sammanfattning

Foumlljande examensarbete beskriver utvecklingen av en IoT-produkt baserad paring dig-italisering av ett smart doumlrrlarings daumlr applikationen ansluts till internet foumlr igenkaumlnningav anstaumlllda som arbetar paring ett kontor Examensarbetet fokuserar primaumlrt paring saumlk-erhetsaspekterna genom att notera de typiska saumlkerhetsutmaningarna som generellaIOT-system utsaumltts foumlr och summerar dessa utmaningar foumlr att utveckla en funktionelloch saumlker produkt fraringn start av projektet

En mikrokontroller vaumlljs ut specifikt foumlr projektet och en testmiljouml byggs foumlr attundersoumlka och motverka eventuella saumlkerhetsbrister

Rapporten ger aumlven detaljerad beskrivning av multi-master databasen Azure Ac-tive Directory och dess betydelse foumlr att uppnaring oumlnskad saumlkerheten i systemet Enny teknik som heter Eddystone introduceras i projektet foumlr att betjaumlna som oumlver-foumlringsprotokoll till Bluetooth-beacons

Det sista steget i detta projekt kompletteras utvecklingen av systemet med Android-applikation som ser till att alla utvecklade delsystem kommunicerar med varandra ochlevererar ett funktionellt och saumlkert floumlde av IOT-systemet

5

6

Contents

1 Introduction 1311 Background 1312 Problem Definition 1313 Purpose 1314 Goals 1415 Research Methodology 1416 Delimitation 1417 Structure of Thesis 14

2 Background 1521 Internet of Things 15

211 IoT Architecture 15212 Foundation Of physical environment in IoT 15213 Basic Structure of Typical IoT Application 16

22 Consumer Internet Of Things 1623 Understanding IoT Security 1624 Security Challenges In IoT Systems 17

241 LAN Mistrust 17242 Environment Mistrust 17243 Application over-privilege 18244 NoWeak Authentication 18245 Implementation Flaws 18

25 Security Solution For IoT Systems 18251 LAN Mistrust 18252 Environment Mistrust 19253 Application Over-Privilege 19254 No Weak Authentication 19255 Implementation Flaws 19

26 The Smart Door Lock 19261 Direct Internet Connection 20262 Automatic Door Unlocking 20263 Other products on the market 21

27 Hardware Review 22271 Microcontroller Unit 22272 Bluetooth Transmitter (Beacons) 22273 Smartphone 22

28 The Software Representation 2229 Computing Concepts 22

291 Cloud Computing Models 22

3 Methodology 2531 Pilot Study 2532 Design Of Prototype 2533 Implementation of the Design 2534 Test Plan 26

7

4 Setting Up A Test environment 2741 Choice of Microcontroller Unit 2742 Choice of Bluetooth Beacons 2743 Test EnvironmentExperimental Design 27

431 Controlling a Door Circuit using a Relay 27432 Test of MCU 27433 Schematic of the electronic door lock 28

5 System Structure 2951 Using Beacons to Monitor User Location 30

511 What is Eddystone 3052 What is REST API 3053 Communicating to and from the REST API 3154 What Is an Active directory 31

541 Using Azure Active Directory to Authenticate Users 31542 What is an Access Token and why do we need it 31

6 Software Development 3361 Android Test Application to connect Google Beacon and Particle Device 33

611 Receiving A String from Beacon to App 33612 Sending A Request from App to Particle 34613 Particle Console IDE 35

62 Creating a Azure AD tenant and Developing Authentication API 35621 Creating A Suitable Test Environment for WebAPI 36622 Creating A Tenant And Users in Azure AD 36623 Authentication API Development 37624 Test Retrieve a token 38

63 Door API Development 38631 Security of API 39632 Connecting to Particle 39633 Test HTTPS from Postman 40

64 Android DevelopmentArchitecture 40641 Using Android framework Components in SDL Application 41642 Application Overview 41643 Integration of Google Beacons 42644 Permissions and requirements 43

7 Result and Analysis 4571 Primary Results 4572 Discussion 47

721 LAN misstrust 47722 Environment misstrust 47723 Application over-privilege 48724 NoWeak Authentication 49725 Implementation Flaws 49

8 Conclusion and Future Work 5181 Conclusion 5182 Ethics Sustainability and Benefits 5183 Risks 5284 Future Work 52

8

List of Figures

1 Infrastructure of Iot ecosystem 162 Naive architecture of the Smart Door Lock 203 Example of house layout where a Bluetooth direction sense algorithm fails

to detect whether the user is inside the building or not 214 Schematic of the working relay The lock is represented as a LED in the

experimental design 285 System Architecture with a base flow of the system and security leakages 296 Communication between android app and Google APIs 347 Basic flow for sending request from Android to particle 358 Retrieving an access token using HTTP request in form of JSON 389 HTTPS request and response from Particle Device 3910 Android Layers 4011 Android App interaction 4212 Message Exchange Using Google Nearby 4313 Current test members of the Active Directory 4514 Request traffic to Google APIs where Nearby API is blue and Proximity

API is green 4515 The APIrsquos request- and error rate 4516 User login UI 4617 Login Successful UI 4618 Particle Spark Console displaying various events relative to the specific Pho-

ton Device 46

9

10

Acronyms

IoT Internet of Things

SDL Smart Door Lock

API Application Programming Interface

DGC Device-Gateway-Cloud

DIC Direct-Internet-Connection

RESTful Representational State Transfer

IT Information Technology

WLAN Wireless Local Area Network

DoS Denial of Service

PIN Postal Index Number

XSS Cross-Site Scripting

MAC Media Access Control

MCU Microcontroller Unit

OS Operating System

SaaS Software as a Service

PaaS Platform as a Service

IaaS Infrastructure as a Service

IO InputOutput

SDK Software Development Kit

HTTP Hypertext Transfer Protocol

HTTPS HTTP over SSL

SSL Secure Socket Layer

LED Light-Emitting Diode

AAD Azure Active Directory

EID Ephemeral Identifier

UID Unique Identifier

URL Uniform Resource Locator

BLE Bluetooth Low Energy

XML Extensible Markup Language

JSON JavaScript Object Notation

11

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 6: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

6

Contents

1 Introduction 1311 Background 1312 Problem Definition 1313 Purpose 1314 Goals 1415 Research Methodology 1416 Delimitation 1417 Structure of Thesis 14

2 Background 1521 Internet of Things 15

211 IoT Architecture 15212 Foundation Of physical environment in IoT 15213 Basic Structure of Typical IoT Application 16

22 Consumer Internet Of Things 1623 Understanding IoT Security 1624 Security Challenges In IoT Systems 17

241 LAN Mistrust 17242 Environment Mistrust 17243 Application over-privilege 18244 NoWeak Authentication 18245 Implementation Flaws 18

25 Security Solution For IoT Systems 18251 LAN Mistrust 18252 Environment Mistrust 19253 Application Over-Privilege 19254 No Weak Authentication 19255 Implementation Flaws 19

26 The Smart Door Lock 19261 Direct Internet Connection 20262 Automatic Door Unlocking 20263 Other products on the market 21

27 Hardware Review 22271 Microcontroller Unit 22272 Bluetooth Transmitter (Beacons) 22273 Smartphone 22

28 The Software Representation 2229 Computing Concepts 22

291 Cloud Computing Models 22

3 Methodology 2531 Pilot Study 2532 Design Of Prototype 2533 Implementation of the Design 2534 Test Plan 26

7

4 Setting Up A Test environment 2741 Choice of Microcontroller Unit 2742 Choice of Bluetooth Beacons 2743 Test EnvironmentExperimental Design 27

431 Controlling a Door Circuit using a Relay 27432 Test of MCU 27433 Schematic of the electronic door lock 28

5 System Structure 2951 Using Beacons to Monitor User Location 30

511 What is Eddystone 3052 What is REST API 3053 Communicating to and from the REST API 3154 What Is an Active directory 31

541 Using Azure Active Directory to Authenticate Users 31542 What is an Access Token and why do we need it 31

6 Software Development 3361 Android Test Application to connect Google Beacon and Particle Device 33

611 Receiving A String from Beacon to App 33612 Sending A Request from App to Particle 34613 Particle Console IDE 35

62 Creating a Azure AD tenant and Developing Authentication API 35621 Creating A Suitable Test Environment for WebAPI 36622 Creating A Tenant And Users in Azure AD 36623 Authentication API Development 37624 Test Retrieve a token 38

63 Door API Development 38631 Security of API 39632 Connecting to Particle 39633 Test HTTPS from Postman 40

64 Android DevelopmentArchitecture 40641 Using Android framework Components in SDL Application 41642 Application Overview 41643 Integration of Google Beacons 42644 Permissions and requirements 43

7 Result and Analysis 4571 Primary Results 4572 Discussion 47

721 LAN misstrust 47722 Environment misstrust 47723 Application over-privilege 48724 NoWeak Authentication 49725 Implementation Flaws 49

8 Conclusion and Future Work 5181 Conclusion 5182 Ethics Sustainability and Benefits 5183 Risks 5284 Future Work 52

8

List of Figures

1 Infrastructure of Iot ecosystem 162 Naive architecture of the Smart Door Lock 203 Example of house layout where a Bluetooth direction sense algorithm fails

to detect whether the user is inside the building or not 214 Schematic of the working relay The lock is represented as a LED in the

experimental design 285 System Architecture with a base flow of the system and security leakages 296 Communication between android app and Google APIs 347 Basic flow for sending request from Android to particle 358 Retrieving an access token using HTTP request in form of JSON 389 HTTPS request and response from Particle Device 3910 Android Layers 4011 Android App interaction 4212 Message Exchange Using Google Nearby 4313 Current test members of the Active Directory 4514 Request traffic to Google APIs where Nearby API is blue and Proximity

API is green 4515 The APIrsquos request- and error rate 4516 User login UI 4617 Login Successful UI 4618 Particle Spark Console displaying various events relative to the specific Pho-

ton Device 46

9

10

Acronyms

IoT Internet of Things

SDL Smart Door Lock

API Application Programming Interface

DGC Device-Gateway-Cloud

DIC Direct-Internet-Connection

RESTful Representational State Transfer

IT Information Technology

WLAN Wireless Local Area Network

DoS Denial of Service

PIN Postal Index Number

XSS Cross-Site Scripting

MAC Media Access Control

MCU Microcontroller Unit

OS Operating System

SaaS Software as a Service

PaaS Platform as a Service

IaaS Infrastructure as a Service

IO InputOutput

SDK Software Development Kit

HTTP Hypertext Transfer Protocol

HTTPS HTTP over SSL

SSL Secure Socket Layer

LED Light-Emitting Diode

AAD Azure Active Directory

EID Ephemeral Identifier

UID Unique Identifier

URL Uniform Resource Locator

BLE Bluetooth Low Energy

XML Extensible Markup Language

JSON JavaScript Object Notation

11

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 7: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

Contents

1 Introduction 1311 Background 1312 Problem Definition 1313 Purpose 1314 Goals 1415 Research Methodology 1416 Delimitation 1417 Structure of Thesis 14

2 Background 1521 Internet of Things 15

211 IoT Architecture 15212 Foundation Of physical environment in IoT 15213 Basic Structure of Typical IoT Application 16

22 Consumer Internet Of Things 1623 Understanding IoT Security 1624 Security Challenges In IoT Systems 17

241 LAN Mistrust 17242 Environment Mistrust 17243 Application over-privilege 18244 NoWeak Authentication 18245 Implementation Flaws 18

25 Security Solution For IoT Systems 18251 LAN Mistrust 18252 Environment Mistrust 19253 Application Over-Privilege 19254 No Weak Authentication 19255 Implementation Flaws 19

26 The Smart Door Lock 19261 Direct Internet Connection 20262 Automatic Door Unlocking 20263 Other products on the market 21

27 Hardware Review 22271 Microcontroller Unit 22272 Bluetooth Transmitter (Beacons) 22273 Smartphone 22

28 The Software Representation 2229 Computing Concepts 22

291 Cloud Computing Models 22

3 Methodology 2531 Pilot Study 2532 Design Of Prototype 2533 Implementation of the Design 2534 Test Plan 26

7

4 Setting Up A Test environment 2741 Choice of Microcontroller Unit 2742 Choice of Bluetooth Beacons 2743 Test EnvironmentExperimental Design 27

431 Controlling a Door Circuit using a Relay 27432 Test of MCU 27433 Schematic of the electronic door lock 28

5 System Structure 2951 Using Beacons to Monitor User Location 30

511 What is Eddystone 3052 What is REST API 3053 Communicating to and from the REST API 3154 What Is an Active directory 31

541 Using Azure Active Directory to Authenticate Users 31542 What is an Access Token and why do we need it 31

6 Software Development 3361 Android Test Application to connect Google Beacon and Particle Device 33

611 Receiving A String from Beacon to App 33612 Sending A Request from App to Particle 34613 Particle Console IDE 35

62 Creating a Azure AD tenant and Developing Authentication API 35621 Creating A Suitable Test Environment for WebAPI 36622 Creating A Tenant And Users in Azure AD 36623 Authentication API Development 37624 Test Retrieve a token 38

63 Door API Development 38631 Security of API 39632 Connecting to Particle 39633 Test HTTPS from Postman 40

64 Android DevelopmentArchitecture 40641 Using Android framework Components in SDL Application 41642 Application Overview 41643 Integration of Google Beacons 42644 Permissions and requirements 43

7 Result and Analysis 4571 Primary Results 4572 Discussion 47

721 LAN misstrust 47722 Environment misstrust 47723 Application over-privilege 48724 NoWeak Authentication 49725 Implementation Flaws 49

8 Conclusion and Future Work 5181 Conclusion 5182 Ethics Sustainability and Benefits 5183 Risks 5284 Future Work 52

8

List of Figures

1 Infrastructure of Iot ecosystem 162 Naive architecture of the Smart Door Lock 203 Example of house layout where a Bluetooth direction sense algorithm fails

to detect whether the user is inside the building or not 214 Schematic of the working relay The lock is represented as a LED in the

experimental design 285 System Architecture with a base flow of the system and security leakages 296 Communication between android app and Google APIs 347 Basic flow for sending request from Android to particle 358 Retrieving an access token using HTTP request in form of JSON 389 HTTPS request and response from Particle Device 3910 Android Layers 4011 Android App interaction 4212 Message Exchange Using Google Nearby 4313 Current test members of the Active Directory 4514 Request traffic to Google APIs where Nearby API is blue and Proximity

API is green 4515 The APIrsquos request- and error rate 4516 User login UI 4617 Login Successful UI 4618 Particle Spark Console displaying various events relative to the specific Pho-

ton Device 46

9

10

Acronyms

IoT Internet of Things

SDL Smart Door Lock

API Application Programming Interface

DGC Device-Gateway-Cloud

DIC Direct-Internet-Connection

RESTful Representational State Transfer

IT Information Technology

WLAN Wireless Local Area Network

DoS Denial of Service

PIN Postal Index Number

XSS Cross-Site Scripting

MAC Media Access Control

MCU Microcontroller Unit

OS Operating System

SaaS Software as a Service

PaaS Platform as a Service

IaaS Infrastructure as a Service

IO InputOutput

SDK Software Development Kit

HTTP Hypertext Transfer Protocol

HTTPS HTTP over SSL

SSL Secure Socket Layer

LED Light-Emitting Diode

AAD Azure Active Directory

EID Ephemeral Identifier

UID Unique Identifier

URL Uniform Resource Locator

BLE Bluetooth Low Energy

XML Extensible Markup Language

JSON JavaScript Object Notation

11

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 8: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

4 Setting Up A Test environment 2741 Choice of Microcontroller Unit 2742 Choice of Bluetooth Beacons 2743 Test EnvironmentExperimental Design 27

431 Controlling a Door Circuit using a Relay 27432 Test of MCU 27433 Schematic of the electronic door lock 28

5 System Structure 2951 Using Beacons to Monitor User Location 30

511 What is Eddystone 3052 What is REST API 3053 Communicating to and from the REST API 3154 What Is an Active directory 31

541 Using Azure Active Directory to Authenticate Users 31542 What is an Access Token and why do we need it 31

6 Software Development 3361 Android Test Application to connect Google Beacon and Particle Device 33

611 Receiving A String from Beacon to App 33612 Sending A Request from App to Particle 34613 Particle Console IDE 35

62 Creating a Azure AD tenant and Developing Authentication API 35621 Creating A Suitable Test Environment for WebAPI 36622 Creating A Tenant And Users in Azure AD 36623 Authentication API Development 37624 Test Retrieve a token 38

63 Door API Development 38631 Security of API 39632 Connecting to Particle 39633 Test HTTPS from Postman 40

64 Android DevelopmentArchitecture 40641 Using Android framework Components in SDL Application 41642 Application Overview 41643 Integration of Google Beacons 42644 Permissions and requirements 43

7 Result and Analysis 4571 Primary Results 4572 Discussion 47

721 LAN misstrust 47722 Environment misstrust 47723 Application over-privilege 48724 NoWeak Authentication 49725 Implementation Flaws 49

8 Conclusion and Future Work 5181 Conclusion 5182 Ethics Sustainability and Benefits 5183 Risks 5284 Future Work 52

8

List of Figures

1 Infrastructure of Iot ecosystem 162 Naive architecture of the Smart Door Lock 203 Example of house layout where a Bluetooth direction sense algorithm fails

to detect whether the user is inside the building or not 214 Schematic of the working relay The lock is represented as a LED in the

experimental design 285 System Architecture with a base flow of the system and security leakages 296 Communication between android app and Google APIs 347 Basic flow for sending request from Android to particle 358 Retrieving an access token using HTTP request in form of JSON 389 HTTPS request and response from Particle Device 3910 Android Layers 4011 Android App interaction 4212 Message Exchange Using Google Nearby 4313 Current test members of the Active Directory 4514 Request traffic to Google APIs where Nearby API is blue and Proximity

API is green 4515 The APIrsquos request- and error rate 4516 User login UI 4617 Login Successful UI 4618 Particle Spark Console displaying various events relative to the specific Pho-

ton Device 46

9

10

Acronyms

IoT Internet of Things

SDL Smart Door Lock

API Application Programming Interface

DGC Device-Gateway-Cloud

DIC Direct-Internet-Connection

RESTful Representational State Transfer

IT Information Technology

WLAN Wireless Local Area Network

DoS Denial of Service

PIN Postal Index Number

XSS Cross-Site Scripting

MAC Media Access Control

MCU Microcontroller Unit

OS Operating System

SaaS Software as a Service

PaaS Platform as a Service

IaaS Infrastructure as a Service

IO InputOutput

SDK Software Development Kit

HTTP Hypertext Transfer Protocol

HTTPS HTTP over SSL

SSL Secure Socket Layer

LED Light-Emitting Diode

AAD Azure Active Directory

EID Ephemeral Identifier

UID Unique Identifier

URL Uniform Resource Locator

BLE Bluetooth Low Energy

XML Extensible Markup Language

JSON JavaScript Object Notation

11

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 9: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

List of Figures

1 Infrastructure of Iot ecosystem 162 Naive architecture of the Smart Door Lock 203 Example of house layout where a Bluetooth direction sense algorithm fails

to detect whether the user is inside the building or not 214 Schematic of the working relay The lock is represented as a LED in the

experimental design 285 System Architecture with a base flow of the system and security leakages 296 Communication between android app and Google APIs 347 Basic flow for sending request from Android to particle 358 Retrieving an access token using HTTP request in form of JSON 389 HTTPS request and response from Particle Device 3910 Android Layers 4011 Android App interaction 4212 Message Exchange Using Google Nearby 4313 Current test members of the Active Directory 4514 Request traffic to Google APIs where Nearby API is blue and Proximity

API is green 4515 The APIrsquos request- and error rate 4516 User login UI 4617 Login Successful UI 4618 Particle Spark Console displaying various events relative to the specific Pho-

ton Device 46

9

10

Acronyms

IoT Internet of Things

SDL Smart Door Lock

API Application Programming Interface

DGC Device-Gateway-Cloud

DIC Direct-Internet-Connection

RESTful Representational State Transfer

IT Information Technology

WLAN Wireless Local Area Network

DoS Denial of Service

PIN Postal Index Number

XSS Cross-Site Scripting

MAC Media Access Control

MCU Microcontroller Unit

OS Operating System

SaaS Software as a Service

PaaS Platform as a Service

IaaS Infrastructure as a Service

IO InputOutput

SDK Software Development Kit

HTTP Hypertext Transfer Protocol

HTTPS HTTP over SSL

SSL Secure Socket Layer

LED Light-Emitting Diode

AAD Azure Active Directory

EID Ephemeral Identifier

UID Unique Identifier

URL Uniform Resource Locator

BLE Bluetooth Low Energy

XML Extensible Markup Language

JSON JavaScript Object Notation

11

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 10: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

10

Acronyms

IoT Internet of Things

SDL Smart Door Lock

API Application Programming Interface

DGC Device-Gateway-Cloud

DIC Direct-Internet-Connection

RESTful Representational State Transfer

IT Information Technology

WLAN Wireless Local Area Network

DoS Denial of Service

PIN Postal Index Number

XSS Cross-Site Scripting

MAC Media Access Control

MCU Microcontroller Unit

OS Operating System

SaaS Software as a Service

PaaS Platform as a Service

IaaS Infrastructure as a Service

IO InputOutput

SDK Software Development Kit

HTTP Hypertext Transfer Protocol

HTTPS HTTP over SSL

SSL Secure Socket Layer

LED Light-Emitting Diode

AAD Azure Active Directory

EID Ephemeral Identifier

UID Unique Identifier

URL Uniform Resource Locator

BLE Bluetooth Low Energy

XML Extensible Markup Language

JSON JavaScript Object Notation

11

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 11: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

Acronyms

IoT Internet of Things

SDL Smart Door Lock

API Application Programming Interface

DGC Device-Gateway-Cloud

DIC Direct-Internet-Connection

RESTful Representational State Transfer

IT Information Technology

WLAN Wireless Local Area Network

DoS Denial of Service

PIN Postal Index Number

XSS Cross-Site Scripting

MAC Media Access Control

MCU Microcontroller Unit

OS Operating System

SaaS Software as a Service

PaaS Platform as a Service

IaaS Infrastructure as a Service

IO InputOutput

SDK Software Development Kit

HTTP Hypertext Transfer Protocol

HTTPS HTTP over SSL

SSL Secure Socket Layer

LED Light-Emitting Diode

AAD Azure Active Directory

EID Ephemeral Identifier

UID Unique Identifier

URL Uniform Resource Locator

BLE Bluetooth Low Energy

XML Extensible Markup Language

JSON JavaScript Object Notation

11

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 12: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

SHA-1 Secure Hash Algorithm 1

IDE Integrated Development Environment

IIS Internet Information Service

OWIN Open Web Interface for NET

UI User Interface

GUI Graphical User Interface

RSA RivestndashShamirndashAdleman

EMC Electromagnetic compatibility

12

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 13: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

1 Introduction

This thesis examines and introduce a technology for a smart door based on the conceptsof internet of things (IoT)

11 Background

With the rapid advancement of the IoT market companies tend to focus on the time-to-market and releasing product as fast as possible instead of developing a secure substantialproduct This leaves many IoT product with inadequate protection against various forms ofmalicious attacks IoT security is an ever growing problem and even if there is a significantamount of research on the topic there is not much substantial work about implementationsor standardizations that could solve this problem

IoT security is of utmost importance as the aftermath of security breaches in IoT canbe devastating A breach in a smart car or smart door lock could lead to stolen productsor even casualties in some extreme cases Even if an undetected breach is not exploitedbut still existing it gives the product owner a false sense of security which is ethicallyunacceptable

Because of the inconsistency of IoT products their architecture and the technology usedit is impossible to develop consistent security measures that cover the entire spectrum ofdifferent devices Therefore shall the IoT products be developed around safety standardsinstead of the other way around

For this thesis we have chosen to work alongside a Stockholm based company calledXLENT to develop a secure smart door lock to access their office The smart door lockwill be our use case in this thesis and will represent the typical IoT device in our society

12 Problem Definition

The security aspect is the highest concern of IoT connected entities The data can bepersonal enterprise or consumer To reach an acceptable implementation for the smartdoor lock (SDL) security should be taken as a major challenge We can summarize theproblems into different questions

1 How do we set-up high and strong authentication between the user point entity(egSmartphone) and the API and will this property provide strong privacy guarantees

2 How do we generate an access token for the user that has privilege to unlock thedoor and how do we secure this token of being exposed

3 Which connection protocols can be used in the product and offers the ability toauthenticate and access control Does the local WiFi network fulfill the securityobligation

4 What kind of microcontroller would satisfy the aims of the product by offering asecure IoT system

5 Which IoT architecture would fit the aim of SDL

13 Purpose

The purpose of this paper is to study and evaluate a suitable set to develop a smart doorlock which is intended to offer high security easy access and control A key challenge thatis faced in this project is the security and privacy of the IoT systems Therefore the paperwill present an extensive investigation for the security and privacy of IoT systems seeking

13

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 14: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

to enhance the lock mechanism by connecting it to the internet making it more robustproductive and innovative

14 Goals

The goal of the project is to construct an IoT system that includes the SDL applicationThe system should be secure and user-friendly The main goal has been allocated to thefollowing subgoals

1 Constructing an architecture regarding the security and functionality

2 Establishing a reliable technique to determine if a user is in the physical proximityof the door lock using Bluetooth

3 Attaining a proper policy to authenticate users trying to access the door

4 Creating an android application that can serve as the user endpoint

15 Research Methodology

Our research was split into two major parts A theoretical and a practical part The theo-retical one was based on a pilot study where we went through the major security concernsregarding IoT devices as well as finding appropriate project scope supporting the goal ofthe project The practical part was to familiarize our selves with the development toolsand environments (eg NET RESTful Android) required fulfilling a functional systemthat considers the security concerns mentioned in the theoretical study

16 Delimitation

The prototype being developed in this thesis is intended to offer high security and easyaccess control The development phase will rather focus on delivering a prototype that iswell-protected against malicious attacks than extensive user functionality This can leadto a product that has high security However it would need some further development andoptimization to fit the purpose of a user-friendly product

17 Structure of Thesis

Chapter 2 contains the background and research study this thesis is based uponChapter 3 contains the planned methodology and working progress used in the project andthesisChapter 4 introduces the test environment used throughout the projectChapter 5 introduces the productrsquos system architecture and explanation of different partsChapter 6 presents the actual development of the system parts presented in chapter 5Chapter 7 contains the result and comprehensive analysis of the finished productChapter 8 is dedicated to further conclusions and relevant information about future work

14

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 15: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

2 Background

This chapter contains the background motivating the thesis as well as the result of theliterature study

21 Internet of Things

Internet of things is a tremendous bias where a huge abundance of sensors and applianceswould be connected to the internet and interact with the cloud Different business appli-cations endure such as vehicles homes buildings machines environmental sensors andso on IoT is growing rapidly and is estimated to comprise 18 billion connected devices by2022 [1] IoT comes in a wide spectrum of different ecosystems all with various require-ments and capabilities For example autonomous cars inherit a highly complex systemwhere system safety and reliability are by far the biggest factors The self-driving carsystem differs significantly from more simple IoT products like a sensor reading systemwhere power consumption and environmental aspects are more of importance

211 IoT Architecture

Understanding the basic principles of IoT is important for providing a functional sys-tem architecture A common architecture of IoT systems usually consists of a three-layerstructure which can be introduced as the edge layer the application layer and the sensorlayer [2] These layers are further discussed below

1 Sensor Layer This layer is considered the lowest layer amongst the three layers andis implemented at the bottom of the IoT architecture It communicates with physicaldevices and segments through smart devices like sensors and actuators which makesit tied to collecting data and controlling the physical world

2 Edge Layer(Network Layer) is the middle piece of the architecture This layer isused to receive the processed information presented by the sensor layer and limitsthe directions to carry the data to the devices and applications that are integratedinto the IoT system This is the most important layer in the system

3 Application Layer This layer is located on the top of the architecture It is used toanalyze interpret and store the collected data[3]

212 Foundation Of physical environment in IoT

The overall structure is represented as we can see in figure 1 It is possible to classify thefoundation of IoT ecosystem into three main parts (1) User interaction point (2) Sensorsamp actuators (3) Delegate amp Relay These three are described below

1 User Interaction Point User interaction point is the dynamic part that connectsthe end user with the end device The objects in this part can be considered as alaptop or a smartphone-controlled by the user The user is capable to control theunit(Smartphone laptopetc) through a 3rd party application that can be installed

2 Delegate amp Relay Some IoT system end devices are supported and upheld by acloud service that gathers the logic for multiple IoT devices This group is liable forthe computation Routers and sensors can also satisfy this position which corpo-rate with the cloud to combine and transfer different co-operations through differentcommunication channels

15

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 16: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

3 Sensors amp Actuators Are the units that are connected to the system and respond tothe commands execute the interaction and changes its state For instance a camerastarts recording Smart Tv turns on a coffee machine begins brewing and so on

Figure 1 Infrastructure of Iot ecosystem

213 Basic Structure of Typical IoT Application

The smart door lock (SDL) is one of the more heavier discussed topics in the IoT sphereas the product is highly dependent on a solid security implementation and maintenanceA breach or compromisation of SDL could lead to severe damage like loss of goods in aburglary or even life threating series of events Smart locks usually consist of the threemajor components an electronic device capable of receiving instruction to open and closesome kind of deadbolt a mobile device sending the instruction and a remote web serverhandling calls to an API andor database

There are two common network system designs for digital home locks the DGC model(Device-Gateway-Cloud) and DIC (Direct-Internet-Connection) DGC rely on the userinteraction point (Mobile application) to act as a gateway to the internet while the DICconnects to the internet directly via the electronic lock device [4] Both architectures followthe same basic principles of the typical infrastructure of IoT device explained in section212

Depending on how the interaction model is implemented a typical user will only see andinteract with the mobile application (User interaction point) where everything essential forthe user will be provided

22 Consumer Internet Of Things

There are two different spheres to the business model concerning the IoT systemsWe definethese two models as business-to-business and business to consumer Business to consumerdelivers the products to the end user whereas business-to-business targets enterprises Ourmain focus in this study will be oriented towards the end-users (business to customer)because they are more exposed to IoT attacks due to the lack of technical expertise anddeployment of protection methods to avoid any potential attacks

23 Understanding IoT Security

As the vast variety of devices can start communicating with each other new business andfunctionality will bloom However as connectivity increases transmissions will be harder

16

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 17: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

to control and more intermediaries will be included in global systems resulting in anexpanded surface of the potentiality for IT attacks Large amount IoT devices will bemade out of simple electronics with no capability of authorization making devices easyto hijack and exploit In a trusted system it can be enough that one intermediate iscompromised for the whole system to break down

When talking about security of IoT devices three particular characteristics are worthmentioning User-centric Internet-connected and Complexity

1 User-centric IoT devices often control actuators and sensors enabling devices tointeract with the userrsquos physical environment IoT systems can process and containsensitive data like user information and behavioral patterns A compromised devicecould lead to serious harm as the device may contain private data as well as itspossible ability control the environment

2 Internet-connected One of the biggest attributes of IoT is also one of its greatestweakness All IoT-devices have a connection to the internet making it exposed toa vast amount of diverse attacks Connectivity can either be direct or indirect Adirect connection indicates that the device gains its access to the internet withoutany intermediaries for instance connectivity access through the cellular networkAn indirect connection means that the IoT device gains access through an existingdevice that is connected to the internet such as an IoT Hub router or a smartphone

3 Complex As IoT devices become more complex with more advanced hardware theyalso expose more vulnerabilities that may be harder to discover and to solve [5]

There have been some concerns regarding the security of IoT systems in the near pastCompanies developing IoT-associated products are principally driven by the time-to-marketrather than developing steady and reliable products There is a vast variety of startup com-panies that rely on producing new functional IoT products on time rather than deliveringa stable and sustainable product It was found that out of 357 companies that specializein home automation 217 have less than 10 employees [5] Focusing on the security of theproduct under developing can then both be expensive and time-consuming making it alesser priority for smaller companies

24 Security Challenges In IoT Systems

A generalization of IoT security attacks can be made into five problem areas describedbelow LAN mistrust Environment mistrust Application over-privilege NoWeak Authen-tication and Implementation Flaws

241 LAN Mistrust

Security in the local network requires the ability to authenticate authorize and accesscontrol However it fails to fulfill the security obligations of the IoT system due to the factof trusting the local WiFi network that the IoT system is connected to meaning that oncethe device is connected and authenticated to the network then it should be trusted Thiswill leave the IoT system exposed to other parties running on authenticated devices[6]

242 Environment Mistrust

As IoT-devices are often positioned in the public realm and are exposed to numerous ofphysical disturbances and adversaries When a device has a naive environmental trust itimplies weak resistance against compromisation within physical mediums An attack ofthis category can be to simply destroy the device or its sensors with violence or sending

17

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 18: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

electromagnetic waves to harm the internal electronics It can also include different typesof techniques to lure the system For an example play a recorded message on a mobilephone in a try to acquire a successive authentication in voice recognition service

In recent years there have been reported cases of DoS (Denial of Service) attacks ondevices with a naive trust in the local environment The attacks used close-range jammingsignals to decrease the signal-to-noise ratio and cause the device to malfunction [5]

243 Application over-privilege

There is a common concept in the world of computer security called The principle of leastprivilege[7] where the privilege of computer program or applications should be minimizedto the least possible needed to perform the programrsquos necessary tasks An over privilegeapplication can lead to potential harm in the form of private data leakage or side channelattacks

244 NoWeak Authentication

Authentication is the process or action of proving or showing something to be true genuineor valid An IoT ecosystem often involves multiple different connections to WiFi Internetand sensors via Bluetooth It is essential that the ecosystem can verify all its connectedparts as well as the API it is connected to otherwise the system will be an easy target formalicious attacks There is also a risk that the system will try to establish and transmitsensitive data to devices outside the proximity of the product Weak authentication isoften a problem in Bluetooth communication as devices either provide no or weak PIN-code authentication that easily can be brute-forced

245 Implementation Flaws

Most successful attacks on IoT are because of implementation flaws in the device Thisattacks often takes form as cross-site scripting(XSS) leakage of hard-coded credentialsopen ports and transmitting sensitive data in plain text [5]

25 Security Solution For IoT Systems

This chapter will shed some light on possible general solutions to increase the securityconcerning the five major problem areas

251 LAN Mistrust

Trust is a vital factor in the implementation of IoT products Trust lays an essential rolein establishing secure communication between the interacting devices There should bean efficient mechanism that defines the trust in an IoT infrastructure As network nodesstart interacting and communicating the need to authenticate and validate the sender ofan incoming message becomes a necessity For an end to end security a possible solutioncould be applying various kind of cryptographic schemes for example broadcasting au-thentication protocol [8] This is achieved by attaching a MAC code to the packet beingsent The receiver end stores the packet without being able to authenticate Later on thesender reveals the keyed Mac to the receiver with a privilege to authenticate the packet[9]Access control is another solution that is discussed but not implemented yet Access con-trol systems offer identification authentication access permission and responsibility forthe entities in the environment through login credentials including passwords PINs andphysical or electronic keys

18

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 19: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

252 Environment Mistrust

Environment mistrust problem can be very common in IoT systems due to that the entitiesor devices can be placed in the public environment Different strategies and methods canbe followed to resolve the problem However the solution is highly dependent on theapplication

253 Application Over-Privilege

This problem takes a place due to the poor scale of the protection mechanism in the devicesthat support multiple application These devices could be the user interaction point andfor instance smartphones A smartphone system can allow any app with a permission toaccess Bluetooth NFC Audio and internet devices The attacker can take advantage ofthis using applications to achieve the manipulation of IoT devices and entities interfacesleading them to perform unapproved operations This problem can be solved by accesscontrol solutions to the operating system in the device (eg smartphones) On the otherhand there are some protocols like FlowFence that aim to practical data protection foremerging IoT application frameworks FlowFence offers an information flow entrance toprevent over-privilege third-party application from manipulating end entities of the IoTsystem [10]

254 No Weak Authentication

A way to tackle this problem is by adding end to end or application level authenticationThis can be approached by a cryptographic secret handshake that enables two parties toverify each other[11]

255 Implementation Flaws

Implementation flaws are a serious problem in IoT devices However the problem takesa place due to the IoT vendors who donrsquot always treat security as a superiority Mostaccess control solutions that help to solve the above problems could also solve possibleimplementation flaws indirectly For instance the suggested solution in NoWeak Authen-tication the cryptographic secrete handshake can protect the IoT device since it wonrsquotenable unauthorized parties to access the device

26 The Smart Door Lock

The smart door lock will control over unlocking the entrance to an office space Theentrance door is located on the third floor inside a large building and connects the officewith a stairwell and multiple elevators The smart lock is expected to handle a heavy flowtraffic as well as maintain a solid functionality in the given environment It is essentialthat the door only unlock itself for authorized people in the space between the stairwellelevator and the door This poses that the door lock needs to have an accurate sense ofwhere the user is located

A naive system overview of the smart door is shown in figure 2 The user applicationwill communicate via Bluetooth to the lock only to tell if a specific user is nearby Boththe lock and the application will have separate communication channels that securelytransmits to the API via a cloud service The API will accept various requests and eithersend commands back to the digital lock andor feedback response to the user application

19

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 20: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

Figure 2 Naive architecture of the Smart Door Lock

261 Direct Internet Connection

The system will implement the Direct Internet Connection (DIC) network design Byfollowing the DIC the system can bypass security challenges such as Revocation evasionand Access Log evasion [4] This is avoided because the lock device is directly connected tothe internet via WiFi instead of relying on the user endpoint for an internet connection Ifthe device has a direct established connection the API and database it can instantaneouslog events and revoke illegitimate digital keys If the system follows the Device gatewaymodel the device will only have access to the internet when an authenticated Smartphoneis in range of the Bluetooth signal emitted by the lock The locking device has then nochance of knowing if an user id or digital key is revoked or not until it may be too late

262 Automatic Door Unlocking

To simplify and improve the usability of the SDL it will support automatic door unlockingThe lock shall be able to sense that an authorized mobile device is nearby and automaticallyopen the door This will pose for two potential security breaches unintentional unlockingand relay attacks

1 Unintentional Unlocking There will be cases where the user is close to the door(and door lock unit) but do not want the door to unlock itself For example the userpasses the door on the inside of the office or enters the building by another door Iflock device senses the authorized user and unlocks the door there is a chance thatan intruder could enter

To avoid unwanted locking there must be some kind of solution to determine theuserrsquos exact location and only unlock the door when the user is in front of it Somesimilar products on the market have approached this matter by creating a Bluetoothdirectional sensing algorithm [4] However this algorithm does not work in somehouse layouts Figure 3 shows an example of a house layout with a digital lockimplemented with directional sensing algorithm As you can see in this layout there

20

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 21: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

are still areas inside the building that can cause unwanted unlocking A study showedthat a smart door lock product using this algorithm unlocked the door 1010 caseswhen an authorized user point was present in the light blue area [4] This is especiallyimportant for the smart lock developed in this project as the lock needs to sense ifthe user is on the correct floor Otherwise an unwanted unlocking could take placeif the user walks around on the story above or below the office

2 Relay Attack is a more sophisticated attack that requires both physical presenceand special equipment from the attacker The basic idea is that two attackers worktogether to record the unlocking signal from an authorized user and then use thesmart lock to grant a successful authorization [12] A typical relay attack case isplayed out in the following steps 1 One of the attackers follows the authorizeduser when heshe leaves the building 2 The attacker then uses an electronic devicethat can receive and record Bluetooth signals from the usersrsquo smartphone 3 Theattacker then relays that signal to the second attacker stationed at the target smartlock 4 The second attacker then transmits the signal to trick the smart lock toopen

It is difficult to build a complete defense against relay attackers You can implementgeographic localization on the application so the smartphone only transmits autho-rized unlocking instruction when it is in range of the lockrsquos working area This onlysolves the problem partially as the smartphone can still be spoofed by the attackersand tricked into thinking that its geographical position is somewhere else by usinggeographical spoofing [4]

Figure 3 Example of house layout where a Bluetooth direction sense algorithm fails todetect whether the user is inside the building or not

263 Other products on the market

There are multiple similar products on the market but none of them fulfill the functionallyrequired for our product Most of them are for private use only more focused on userexperience simplicity or futuristic design and fails to explain the security of their prod-uct This is problematic as it gives the product owner no acknowledgment on how securetheir smart door lock really is We will therefore aim to create a lock with motivatedand transparent security solutions without disclosing any vital information concerning thesecurity of the product

21

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 22: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice

27 Hardware Review

This project will rely on three major hardware components a microcontroller unit ABluetooth transmitter and a smartphone device

271 Microcontroller Unit

The microcontroller unit is an embedded system that contains inputoutput pins where wecan connect it to the object that wersquore trying to work against to achieve the functionalityneeded To develop the functionality of locking and unlocking the door a microcontrollerunit would be essential to serve the objective of the project as it can receive a signal andinterpret it to do a specific functionality

272 Bluetooth Transmitter (Beacons)

This project will use Bluetooth for sensing nearby user For sending a strong and stableBluetooth signal into the nearby environment an antenna must be used Some MCUrsquos havean already built-in support for sending and receiving Bluetooth transmissions Howeverthis supports are often unreliable and will not carry the structure of this project Insteadthe actual Bluetooth transmissions within this project will be completely separated fromthe MCU unit This is achieved by implementing so-called Bluetooth Beacons TheseBeacons contains small processors batteries antennas and are specialized for handlingBluetooth communications

273 Smartphone

To debug the mobile application developed in the project a mobile smartphone device mustbe used This device needs to support applications of the Android OS and must supportInternet- and Bluetooth communication In this project a Samsung Galaxy 3 is used

28 The Software Representation

The architecture of software gives a significant understanding of the system under devel-opment It shows how the system is divided into subsystems It tells which problem thesystem can solve and wherein the system each problem is solved To start with the soft-ware development an architectural pattern is needed to divide the system into subsystemsThis division is helpful to avoid mixing code Without such division it is is easy to tanglethe user interface code with the business logic code in the same method

29 Computing Concepts

There are many computing concepts like Grid computing Cluster computing andCloud computing In our design wersquoll be choosing the cloud computing cloud comput-ing is a computing standard where several entities of a system are connected to a private orpublic network It provides dynamically scalable support and foundation for applicationdata and file storage which would serve the aim of our applicationSDL[13]

291 Cloud Computing Models

1 Software as a Service(SaaS) In this model a complete application is offered to thecustomer as a service on demand To say highly scalable internet based applicationsoffered on the cloud and offered as services to the end user (eg Google Docs)

22

2 Platform as a Service(PaaS) a layer of software or development environment is en-capsulated amp offered as a service Here the platform is used to design develop buildand test applications and are offered by the cloud infrastructure(eg Azure ServicePlatform Google App Engine)

3 Infrastructure as a Service(Iaas) IaaS provides basic storage and computing capabil-ities as standardized services over the network It is a pay per use model Services likestorage and database management are offered on demand(eg Amazon Web Services)

23

24

3 Methodology

This chapter contains the methodology and the basic foundation used to carry out thisproject The project is based on four main phases Pilot Study Design of PrototypeImplementation of Design and Testing The first two steps will be completed in the givenorder while the last two steps will be implemented iteratively This structure will hopefullyhamper risks and inconveniences associated with the project such as wrongly implementedcode or misgivings regarding the prototype It will also give a greater understanding ofthe problem definition and will help set the projects outlines and delimitations

The methodology is based upon the iterative and incremental development build modelwhich will allow the project to be more agile and adaptive for changes in mid-developmentEnabling a test-driven and flexible development is particularly important in projects wheremultiple system parts are obliged to communicate with each other

An agile methodology was therefore chosen instead of applying methodologies such asthe waterfall model which has a rigid non-iterative approach

31 Pilot Study

A research study was conducted before the phase of design and implementation Theresearch aimed to understand the nature architecture and security challenges of imple-menting an IoT product

Gathering sufficient information regarding the two main themes of this thesis Thearchitecture design of common IoT applications and the security challenges faced by IoTentities The first task consisted of figuring out the common architecture of IoT systemsand understanding the main three layers that are mentioned in the pilot study leading usto set-up a foundation of the physical environment and classifying the overall structure forour own IoT system represented by the smart door lock The second main subject thattook a place in the pilot study was understanding the security aspects of IoT systemsSince there are a vast variety of devices that are communicating with each other resultingin expanded breach and possibility for harmful attacks on the system a main focus onthe security aspects seemed reasonable and relevant We tried to sum up the securitychallenges and generalize the attacks to set a list of requirements that are needed to betaken and considered when developing an IoT system

32 Design Of Prototype

A complete specification for the prototype is derived and considered from the pilot studyDesign choices take regard to the common architecture of IoT systems and the securitychallenges The preferences comprised of a suitable microcontroller that would serve thefunctionality of the SDL wireless devices transmitting a continuous radio signal which canbe detected by smart devices (eg Smartphone) via a connective protocol (eg Bluetooth)a cloud that can contribute in a secure and stable communication and an API that wouldbe able to handle the functionality of the SDL

33 Implementation of the Design

The phase of development and implementation is conducted with an iterative strategy toconstruct the prototype that would match the specifications of the design By breakingdown the design into small chunks we are able to develop and test in repeated sequencesIn each iteration new features can be developed and tested until we have a fully functionalsystem that fulfills the purpose of the thesis

25

34 Test Plan

An elaborate test plan that encapsulates all the functionality of the prototype will bewritten The test plan is used to verify that the prototype lives up to the expectation andthe overall quality requested by the stakeholders

The goal is to continuously update and develop the test plan parallel to the implementa-tion of the design This will lead to an iterative working environment where implementationcontinuously will be tested against the testbench The ideal goal is that the prototype willhave an evaluated test for every state of the running implementation

We aim to restrict the tests to three main categories Software Tests Hardware testsand Conclusive-End tests where the final prototype combined with both hardware andsoftware will be tested The results of the tests will strictly focus on functionality butmore importantly security This will influence the way we write tests and the test planitself Results of the hardware and software tests will mostly be used to collect data forfurther development while the end tests will be neatly analyzed for future research andconclusions

26

4 Setting Up A Test environment

The Smart lock is exposed to moderate traffic during the days by installing a partiallyworking lock to the door for testing is far from optimal and will lead to unreliable resultsInstead we chose to create a test environment that represents a real user scenario andwhere the product can be tested systematically during the developing phase of the project

41 Choice of Microcontroller Unit

There are multiple of different microcontrollers (MCU) on the market that will fulfill ourdemands on the hardware We want a secure and robust MCU with the ability to stayinternet connected The Arduino hardware is a well-established choice that has muchtechnical documentation and has an easy internet setup However the Arduino is moretargeted to the hobby user and has a lot left to wish for security-wise Instead we decidedto implement our door lock with the Particle Photon device The Particle Photon is asmall yet powerful IoT -device that can handle both WiFi and Bluetooth communicationThe Photon offers multiple IO pins and a processor powerful enough to handle the logicneeded for this project The Photon provides a well developed and robust SDK withmultiple tools for easy configuration of the device All communication tofrom the devicewill go through the Spark -cloud with secure HTTPS transmissions and token handlingUsing Photon would improve the security of the prototype being designed as well as savinga significant amount of resources otherwise spent on developing a similar solution

42 Choice of Bluetooth Beacons

A Bluetooth beacon has a relatively simple hardware structure The purpose of the bea-con is simply to transmit a Bluetooth signal to its surroundings The beacon should beconfigurable to the point that an administrator can modify the beacon-transmitting dataincluding the transmitting power and ID-tag of the beacon

The Estimotersquos Bluetooth beacons fulfill our demands and have all the functionalityneeded for the design being developed The Beacons comes with a reliable interface for con-figuration and well-documented SDK for multiple different platforms The beacons supportthird-party Bluetooth transmissions protocols granting more options to developers

43 Test EnvironmentExperimental Design

This subsection introduces a test environment applied for examining the progress andimprovement of the system

431 Controlling a Door Circuit using a Relay

A relay has two circuits a control circuit and a load circuit When the control circuit isturned on current starts flowing through a coil it generates a magnetic field that attractsthe armature and the load circuit is closed A relay can be used to control different circuitsby one signal Relays are used whenever it is necessary to control high power or high voltagewith a low power circuit Low power devices as microprocessors can drive relays to controlelectrical loads beyond their direct drive

432 Test of MCU

The Photon MCU was used to test a basic functionality within the design A test programwas written to control a LED on the microcontroller itself Thereafter a test environmentwas set up on a breadboard to control an external LED using a relay that controls the

27

high voltage coming from the source The microcontroller would interpret the signal todetermine whether turning onoff the LED (figure 4)

433 Schematic of the electronic door lock

Figure 4 Schematic of the working relay The lock is represented as a LED in theexperimental design

28

5 System Structure

This chapter describes the final system structure and user base flow figure 5

Figure 5 System Architecture with a base flow of the system and security leakages

1 Android Application asks for authentication by sending username and password viaHTTPS

2 Auth API ask for an access token from Azure AD with provided user credentialsresourceID and clientID

3 If the information sent with the request is valid the Azure AD responds with anaccess token valid for 2 hours

4 The token is sent back to the Android Application via HTTPS The Android clientcan now make authenticated calls to the Door API

5 The Android application will start listening for registered beacons When a Beacontransmission is received the application will confirm that the beacons are from avalid source

6 The Android will request to open the door if the beacon validation is successfulAccess token and the function name is provided in the HTTPS call

7 The door will send a new HTTPS request to the particle if the received request isauthenticated and authorized The request to Spark Cloud will contain the uniqueaccess token and deviceID for the Particle device

8 Spark will send the specific function call (in this case open door) to the device withthe correct deviceID

29

9 The Photon device will return a specific value of the function called was executedcorrectly or not

10 Spark Cloud will send an HTTPS response back to door API containing informationabout the status of the request

11 Door API sends a response back to Android telling the application if the request wassuccessful or not

51 Using Beacons to Monitor User Location

The project will use multiple location Beacons from a company called Estimote TheBeacons uses Bluetooth Low Energy technology and supports a numerous different trans-missions protocols Both Apple and Google offers their own widely popular Beacon trans-mission technology this project will rely on Googlersquos open format called Eddystone

511 What is Eddystone

Eddystone is an open free to use transmission protocol developed for Bluetooth beaconsand is compatible with both Android and IOS Eddystone support four major packet formatto transmit data

1 Edddystone-UID consist of a simple format where each Beacon contains a names-paceID and and a specif InstanceID

2 Eddystone-EID works similar to UID but pseudo-randomly generates a new iden-tification with a developer set lifetime The 8-byte identification string is also AES-encrypted

3 Eddystone-TLM sends telemetric data from the beacons sensors such as temper-ature battery status or atmospheric pressure

4 Eddystone-URL sends a given URL to its environment [14]

The Eddystone Ephemeral Identifier (EID) is an excellent choice for this project Thisformat gives control to choose which clients can make use of the beacon signal and canonly communicate with those that have the same encryption key as the beacon This willtherefore generate prevention of other parties using the beacon It will also preserve theintegrity of the application as well provide a reliable signal for users in a specific area thatis not easily spoofed [15]

52 What is REST API

Representational state transfer technology (REST) is a software architectural approachand procedure used for the goal of communication in web-based services REST is anAPI that uses HTTP requests to get post put and delete data This API uses HTTPparadigms REST API uses GET function to regain a resource PUT function to changethe nature ofupdate a resource which can be a block of information or a file POSTfunction to create a resource and DELETE function to remove it This API structureis important to minimize the coupling between the client and server components in adistributed application REST is an interface between systems using HTTP to obtain dataand generate operations on these data in all possible formats (eg XML and JSON)[16]

30

53 Communicating to and from the REST API

To make different calls via the internet can be dangerous from a security perspective but isin our cause definitely necessary The Particle door device needs to be fed different tasksas door unlocking to be able to perform in a wanted manner

When transmitting data via the web the sender has no control over which path itchooses takes to reach the receiver This means that nodes on the internet can interceptthe data and read it if it is not encrypted in some kind of way The most standard protocolfor receiving or requesting data over the web is HTTP (Hypertext Transfer Protocol) Thestandard HTTP protocol comes in various forms and has all the functionality needed forcalling our web APIs However there is one major problem the HTTP sends data viaplain text This is a large issue as anyone interacting the HTTP request on its path theresponse can easily read or intercept data without us ever knowing This will make all thesecurity measures we implement useless and unnecessary as an attacker simply can read allthe communication within the system extracting sensitive data as username passwordsor tokens

Fortunately there is a simple solution to this problem called SSL (Secure SocketsLayer) By combining these two protocols you get a safe and secure protocol with all thefunctionality of the HTTP this protocol is called HTTPS HTTPS relies on asymmetric andsymmetric cryptography and all the data send between two nodes a completely encrypted

54 What Is an Active directory

Active directory is a distributed multi-master database where we can store informationabout our computers users and security groups The AD can perform some functionalityto serve the goal of the project being developed (eg Authenticate users and computerswhen the user tries to get on to the system)

541 Using Azure Active Directory to Authenticate Users

Azure Active Directory is a cloud-based authentication manager produced and maintainedby Microsoft The service offers a highly secure and functional identity management tocompanies as well as to private users By deploying a Web API integrated with ActiveDirectory to the Azure cloud you can save a large number of resources and simultaneouslyincrease the overall security of the product

We choose to implement the Azure AD into a separate Web API This API will handleauthentication of the user and send back a valid access token to the mobile applicationBy receiving the userrsquos login credential (username and password) by secure HTTPS postmethod the API will establish a connection with the active directory service and forwardthe credential to the AAD The AAD will then check the credentials for validity andreturn a custom access token with encrypted information containing the userrsquos objectIDuser scope and what resource the user should be able to access We choose to separate theauthentication outside the android application to give less control of the authenticationflow in the mobile application In this way we gain more control over the login forms andbasic flow of the mobile application It will also make it easier to update and edit theapplication as well as making it easier to implement applications to different platforms

542 What is an Access Token and why do we need it

An access token is an object that is implemented in the security context when workingauthentication It is considered a credential that can be used by the client to access aspecific API it is considered as a unique string containing letters and numbers where thisstring is passed with every API call The information in a token includes the identity of

31

the user associated with the process being performed(eg Authentication) The purpose ofthe access token is to notify the API that the beneficiary of this token has been authorizedto access the API and perform a specific operation

32

6 Software Development

This chapter explains the development phase of this project The chapter is split intosix sub-chapter where each chapter represents an iteration ordered in a chronologicalapproach

61 Android Test Application to connect Google Beacon and ParticleDevice

A simple Android application was developed in this iteration in trying to set up a suitabletest environment to experiment the basic functionality flow by sending a request from theAndroid app to spark cloud where we have written simple test code to turn on a LED

611 Receiving A String from Beacon to App

As we were exploring different alternatives for establishing the communication betweenthe Bluetooth beacons and mobile phone application we realized that Google offered abetter alternative to our solution Estimote has its very own SDK that worked well for ourpurpose however we made the decision to work with Googlersquos alternative for a numberof reasons The main reason was that Google offers more securely and robust platformfor handling beacons It has a larger more documented SDK and an excellent integra-tion with its own mobile platform Android it also offers full support for the Eddystonecommunication protocol

To setup solid beacon communication between a smartphone and beacons we used twoof Googlersquos cloud-based APIs called Google Proximity Beacon API and Google NearbyAPI To create a working communication you need go through following steps

1 Firstly you need a google account and create a project in Googlersquos Cloud API Plat-form and then allow the fresh project to use Proximity Beacon API and GoogleNearby

2 Use Google Platform to register the Beacons that will be used in the project Theplatform offers an extensive view over all registered beacons used in the specif projectand will link them together with the application In that way you will reduce thelikelihood of unwanted communication with other unregistered beacons and enhancetherefore enhance the overall security of the solution

3 Establish a unique connection between our Android Application and Google CloudAPI Platform We want to make sure that only our specific android application hasthe allowance to talk to our private Beacon Platform Otherwise we face to riskthat other application or endpoints exploits our API and begins to alter the beaconstransmission behavior such as data payloads transmission power or even changingthe Beacons unique ID string To this you need the create a unique API key inthe cloud platform and link it to the Android application manifest The androidapplication will use this key to contact our specif API link to the project To makesure that the API only allows communication request from our application we needto give the API the unique SHA-1 fingerprint generated by the Android application

4 Now we have to generate code in the android application to tell it to start to com-municate with Googles API This can be done in multiple ways we choose to doit by creating an instance of the GoogleAPIClient What this basically does is tocreate an object that will connect to the specific Google service you want to useFollowing code establish a connection to Google Nearby API that will later use to

33

receive string messages from the beacons We should now have a secure connectionwith the Google API

Figure 6 Communication between android app and Google APIs

1

2 pr i va t e void CreateGoogleApiCl ient ( ) 3 i f ( mGoogleApiClient == nu l l ) 4 mGoogleApiClient = new GoogleApiCl ient5 Bu i lder ( getAppl i cat ionContext ( ) )6 addApi ( Nearby MESSAGES_API)7 addConnectionCal lbacks ( t h i s )8 addOnConnect ionFai ledListener ( t h i s )9 enableAutoManage ( th i s t h i s )

10 bu i ld ( ) 11 mGoogleApiClient connect ( ) 12 13

Listing 1 CreateGoogleAPIClient

To actually receive and interpret messages from the beacons we need to configurethe beacons to send the right kind of data in the right protocol format we also need toimplement some more code in the Android application Using the Estimote configurationapplication we allow the beacon to start sending string messages via the Eddystone-UID(a protocol explained in the previous chapter) We then implement a Nearby messageslistener in the Android application The listener starts to look for messages using thesmartphone Bluetooth antenna and Bluetooth BLE technology If it finds a message sentfrom a known beacon ID it will log it for us in the Android Studio IDE console

We debugged the project on a smartphone using Android OS and received strings fromtwo unique beacons

612 Sending A Request from App to Particle

Setting up a simple layout for the Android app by designing a button to send the request toturn on the led on the spark cloud that belongs to the particle photon microcontrollerWeused Particle Android Cloud SDK which is an easy-to-use wrapper for the Particle RESTAPI The SDK enables interaction and synergy between our Android app and Particle-powered connected microcontroller via the Particle Cloud However publishing eventsfrom the Android app directly to the particle cloud would be a problem because we willbe exposing our login credential which were hardcoded in plain text in the Android app

34

Figure 7 Basic flow for sending request from Android to particle

1 pub l i c void l o g i n ( ) 2 Async executeAsync ( Par t i c l eC loud get ( S t a r tAc t i v i t y t h i s ) new Async

ApiWorkltPart ic l eCloud Object gt() 3

4 pr i va t e Pa r t i c l eDev i c e mDevice 5

6 Override7 pub l i c Object c a l lAp i ( Par t i c l eC loud sparkCloud ) throws

Part ic l eCloudExcept ion IOException 8 sparkCloud l og In ( xxxxxxxxxxxgyyyyyy com xxxxxxxxxx ) 9 mDevice = sparkCloud getDevice ( xxxxxxxxxxxxxxxxxxxxxx )

10 re turn minus111 12

13 Override14 pub l i c void onSuccess ( Object va lue ) 15 Toaster l ( S t a r tAc t i v i t y th i s Logged in ) 16 Checks i f we can connect to dev i c e a f t e r l ogg ing on17 i f (mDevice i sConnected ( ) ) 18 In tent i n t en t = new Intent ( S t a r tAc t i v i t y th i s

RemoteContro l l e rAct iv i ty c l a s s ) 19 i n t en t putExtra (ARG_DEVICEID xxxxxxxxxxxxxxxxxxxxxxx ) 20 s t a r tA c t i v i t y ( i n t en t ) 21 e l s e 22 Toaster l ( S t a r tAc t i v i t y th i s Unable to connect dev i c e ) 23 24 25

26 Override27 pub l i c void onFa i lure ( Part i c l eCloudExcept ion e ) 28 Toaster l ( S t a r tAc t i v i t y th i s Something has gone ho r r i b l y wrong

) 29 30 ) 31

Listing 2 Writing login credentials in the Android App

613 Particle Console IDE

Particle has an Integrated development environment IDE enabling the user to develop thesoftware for the microcontroller in an easy-to-use application Every particle device has aunique ID where the user can bind the code with the exact unique particle

62 Creating a Azure AD tenant and Developing Authentication API

Next iteration of the project was to develop the web API extending the product We choseto use Microsoftrsquos framework for REST API because of the offered simplicity and great

35

cohesion with the Windows OS We started by establishing a simple test environment fordebugging the APIs and then began to develop the API handling the authentication of theusers After testing the authentication API by receiving a legitimate access token from theAPI we started to develop the door API This iteration ended with an iterative test of thecomplete system deployed to the internet

621 Creating A Suitable Test Environment for WebAPI

It is essential to create an elaborated test environment to enable a test-rich developmentTherefore we needed to test our solution locally on the computer to make sure that wehave a functioning test before publishing the solution on the cloud To do this we wantto allow our computer to run programs on the localhost which is a hostname of thecomputerrsquos local loopback network interface This allows us to send various HTTP requestto the WebAPIs locally without deploying an unfinished product to the web The test anddevelopment of the APIs conclude of three major parts

1 MS Visual Studio The Azure cloud is developed and maintained by Microsoft andis highly compatible with their own IDEMicrosoft Visual Studio Visual Studio offersa thorough debugging tool project templates and a build in easy deployment tool tothe Azure cloud Visual Studio also works well with the Windows IIS manager andis for this project an suiting testing and developing tool to use

2 Windows Internet Information Service To enable Windows to host a local serveron the computer you need to enable and install the Windows native tool InternetInformation Service (IIS) and its configuration manager The service offers loads ofuseful tools and alternatives and allows an easy setup for running your own localserver

3 Postman To test the solution both locally running as well as the deployed solutionwe need an easy interface to send and receive different HTTP forms There aremany tools and program for doing this and we chose to use Postman for this specificpurpose Postman gives an easy to understand interface with all the functionalityneeded for elaborate testing of the APIs

A test project was later created for an educational purpose A template project of asimple web API was deployed to the localhost which responded to HTTP-get request byreturning static numerical values in form of XML or JSON data

622 Creating A Tenant And Users in Azure AD

In a physical workplace the term tenant can be described as a company or organizationthat occupies a building This building may contain different organizationscompanies orin another word different tenants In Cloud enabled workplace a tenant can be interpretedas a client or organization that owns and manages a particular instance(Blueprint) of thatcloud service(In our case Azure AD)

With the identity platform provided by Microsoft Azure a tenant is simply a dedi-cated instance of Azure Active Directory (Azure AD) that an organization receives andowns when it signs up for a Microsoft cloud serviceA tenant is responsible for the usersof an organization and their credentials (eg passwords user profile data permissions) Italso contains groups applications besides offering security for the organizationCreating atenant through Azure AD helps us to control and manage the applications being createdand registered in the AD Wersquoll be creating two different applications which are the Au-thentication API (defined as Native API ) and the Door API (defined as Web API)under the same tenant to say that the two applications belong to the same service

36

bull What is a Native API and what differs it from a Web APINative client web API diverge from a common web API because it is installed ona cloud while web API is accessed through a browser Native clients have theadvantage of asking for an access token from Azure AD meanwhile a Web API canissue that access token offered by the native client API from Azure AD The nativeclient API is a Restful API that has the advantage to ask for an access token fromAzure Active directory because it is configured with the Azure AD AuthenticationLibrary (ADAL) contrariwise from the web API that canrsquot be configured with thesame library

623 Authentication API Development

Authentication is the process of determining whether someone or something is listed andeligible The process of Authentication is simply comparing the credentials provided by auser to the ones in the database of authorized users If the credentials match the procedureis executed and the user is granted a permission to access In an IoT scenario like oursthis process is a vital and crucial process to serve the purpose of this project in securitymatters We built an authentication REST API to facilitate the interaction withfromany platform(eg web API mobile app) We used HTTPS authentication to get an accesstoken in our REST API We created a constructor that has the authentication contextwhich is the authority represented by the tenant and the URL instance for login in Azureactive directory Using the authentication context wersquoll be acquiring an access token fromthe authority on the behalf of user passing necessary claims for authentication as below

1 ClientId Identifier of the client requesting the token

2 ResourceId Identifier of the target resource that is the recipient of the requestedtoken

3 User Credentials Username and password

When the process of Authentication is completed and permission has been granted theuser retrieves an access token to complete the authorization

1 [ HttpPost ]2 [ Route ( api authent i ca t e ) ]3 pub l i c IHttpAct ionResult Authent icate ( Creden t i a l s c r e d e n t i a l s )4 5 var authContext = new Authent icat ionContext ( Authority new

TokenCache ( ) ) 6 var userPasswordCredent ia l = new UserPasswordCredent ia l (

c r e d e n t i a l s Username c r e d e n t i a l s Password ) 7 Authent i cat ionResu l t r e s u l t 8 t ry9

10 r e s u l t =11 authContext AcquireTokenAsync ( res c l i e n t I d 12 userPasswordCredent ia l ) Result 13 14 catch ( AdalException ee )15 16 re turn BadRequest ( ) 17 18 re turn19 Ok(new AuthResult20 21 Token = r e s u l t AccessToken 22 ExpiresOn = r e s u l t ExpiresOn

37

23 ) 24 25 26

Listing 3 Authenticate to get an access token

624 Test Retrieve a token

To test the functionality of our Authentication API we sent an HTTP post request to ourlocal host using postman which is a developer tool utility to test API calls we use a URLencoded form and expect to retrieve the access token from the API in the form of JSONstringConfigurable token lifetimes in Azure Active Directory We faced a problem withthe lifetime of the access token that was expired as soon it was released when we tested itso we had to configure the lifetime of the token We used the policy object that representsa set of rules that are enforced on individual applications or on all applications in anorganization using PowerShell modules we were able to change the lifetime of an accesstoken and extend it to two hours

Figure 8 Retrieving an access token using HTTP request in form of JSON

63 Door API Development

After making sure that the authentication API worked properly we started to develop theAPI handling the actual request to the Particle device Mainly we want to handle thecommand that tells the hardware to open the door This command will be received byHTTPS from the Android application the API should be able to interpret the commandand create its own HTTPS request and send it to the particle To ensure that onlyauthenticated sources can send requests to the API we need to enable some security featuresin the API first

38

631 Security of API

Building an authorized dependent REST API is common practice and thatrsquos why thereis an easy-to-implement template option in Visual Studio for this specific purpose Thetemplate wraps the API in an Owin (Open Web Interface for NET) middleware to en-able authorization in an easy and straight-forward way The Owin code will be executedin the API start-up code which is separated from the APIs own logic The only directconfiguration needed is to make sure that both APIs are connected to the same tenantand that DoorAPIrsquos ClientID matches the RecourceID in the authentication API Theauthorization of the API should work correctly at this point

The ASPnet has powerful filter properties which filter out requests received from dif-ferent sources and data forms For example there is an [HTTP GET] filter which tellsthe API that only request in the form of [HTTP GET] will be accepted and processedby the API There is also a [Authorize] filter which works in the very same way it filterouts all requests not containing a valid access token This is a very simple but powerfulway to tell the API which functions classes or data that only should be accessible byauthorized requests

632 Connecting to Particle

There are multiple ways to communicate with the Particle device the two most commonand efficient ways it to use Particlersquos SparkSDK to establish a running connection tothe Particle device the other way is to use authenticated HTTPS request Both ways arecompatible with the project but choosing HTTPS over the SparkSDK has some advantagesHTTPS is more configurable easier to understand and debug it is also very compatiblewith C and ASPNET in general It gives more control over the transmission as HTTPSis securely encrypted by SSL certification

The HTTPS request sent to Particle must include some specific data for it to successPicture 9 display a simple function call to the Particle device from Postman

Figure 9 HTTPS request and response from Particle Device

Code for an identical request can be implement in C with Visual Studiorsquos SDKNetHTTP as listing 16

1 pub l i c async Tasklts t r i ng gt ConnectPart ic leAsync ( )

39

2 3 HttpCl ient c l i e n t = new HttpCl ient ( ) 4 var ct = new ListltKeyValuePairlts t r i ng s t r i ng gtgt() 5 ct Add(new KeyValuePairlts t r i ng s t r i ng gt( access_token _accessToken ) ) 6

7 HttpRequestMessage r eques t = new HttpRequestMessage ( )8 9 RequestUri = new Uri ( _baseUrl + _deviceID + + _function )

10 Content = new FormUrlEncodedContent ( ct ) 11 Method = HttpMethod Post12 13 var re sponse = await c l i e n t SendAsync ( r eque s t ) 14 re turn response ToString ( ) 15

Listing 4 HTTPS request in i C

633 Test HTTPS from Postman

This iteration ended with HTTPS-test The goal was to turn on the led through anauthenticated HTTPS-post sent to the Door-API

64 Android DevelopmentArchitecture

Android is an operating system which can be found on a variety of different modern devicesand considered one of the most popular OS on smartphones Android is a Linux-based OSand it is composed of a stack of software components which are roughly divided into fourlayers where the Linux kernel lies at the bottom layer and provides the abstraction betweenthe device hardware(eg camera display) On the top of the Linux kernel layer is a set oflibraries including open-source web browser engine making it the second layer following itwith the third layer which is the Application Framework layer presenting various higher-level aids to applications in the form of Java classes The last layer which is the top layeris the Android Application layer where the developers are being able to write their appsand install it on this specific layer[17]

Figure 10 Android Layers

40

641 Using Android framework Components in SDL Application

Android uses a component-based framework for building efficient applications These com-ponents can be seen as sets of building blocks that connect with each other by the usageof intents This enables developers to build effective and reusable code that inherits allthe essential functionality from the framework In the SDL application two major compo-nents are used MainActivity and BackgroundService The two components are declaredin separate classes and inherit its behaviors from different superclasses from the Androidframework The MainActivity class is derived from the superclass AppCompatActivityThis inheritance tells the application that MainActivity is an Activity-component that isbackward compatible with earlier versions of the Android SDK

Activity components are fundamental for android development and handle the inter-action with the users of the application Activities are running on the application singleUI-thread that is only active when the user directly interacts with the specific applicationThe usage of activity extends to show the users graphic interfaces and are directly con-nected with Androidrsquos XML layouts These layouts purpose is to display various graphicalinformation to the user through the smartphonersquos screen When a user starts an applica-tion a preset activity life-cycle will start and will handle the startup process of the appand draw the user interface on the screen Activities are powerful components with theability to handle all the functionality of an application however implementing all the logicin activities is usually a bad practice as activities often are battery-consuming and do notpossess the ability to run in the mobile unitrsquos background

For creating longer running operations the Service component should be used insteadof Activity These components can run on separate threads in the background hiddenfrom the applicationrsquos user Services can still be active even if the user decides to close theapplication or lock the smartphone For an example this will enable the application toscan the nearby environment for beacons without requiring the user to interact with theapplication

The functionality of the Smart Door Lock application can therefore be divided intotwo separate component MainActivity and BackgroundService The MainActivity classwill handle both the startup and login process and will also establish a connection withGooglersquos APIs The service BackgroundService is then called from MainActivity to startrunning in the background of the phone The BackgroundService sole purpose is to scanfor beacons and send appropriate requests to the DoorAPI if a valid beacon is detected

642 Application Overview

Following the Structure in figure 11 The SDL app will be requiring the user to enterthe login credentials (username password) Clicking on the login button will activate theonClick() method that in turn will go to our MainActivity and trigger an HTTPS requestthrough the HTTPS client The credentials will be sent in a scrambled message withan agreed code between the sender and the receiver (Authenticate API in our case) andtransferred on a Secure Sockets Layer where no one can read the message The userrsquoscredentials are authenticated in API when the Authentication process is completed andsucceed the Access Token is sent back to the MainActivity in the SDL app At this pointthe app is ready to start the Background service and begin to scan for beacons Whena valid beacon is found an authenticated request is sent (containing the acquired AccessToken) through the HTTPS client to the Door API where the validity of the token isdetermined A proper response is then sent from the Door API telling the application ifthe request was successful

41

Figure 11 Android App interaction

643 Integration of Google Beacons

The integrating beacons in the application can be divided into two main parts The bea-con initialization part and the message listening part In the startup a Google client iscreated as described in the previous chapter 612 when the client is successfully con-nected to Googlersquos APIs the subscription service BackgroundService will start running ina background thread The beacon handling is dependent to two important APIrsquos createdby Google called Nearby Messages and Google Proximity API

Nearby Messages is an API that allows different units supporting wireless communi-cation to send messages to each other Google nearby sends these messages through theweb instead of sending them directly via Bluetooth Google Proximity API allows beaconto use the Nearby Messages API by associate data to registered beacons as attachmentThese attachments can then be read as messages by other registered devices

Following sequence describes typical message exchange event in this project and followsthe numeration of figure 12

1 A beacon is placed in the proximity of the door lock This beacon will transmit asecret token associated with a data payload The token is synced and registered bythe Google Proximity API

2 A user with a smartphone running the SDL Applicationrsquos BackgroundService startsto subscribe for beacon messages

3 The user walks into the beacon transmission range the smartphone application re-ceives the beacon broadcasting token

4 The application contacts Google Nearby API to check if the token is valid or notThe application will also send its generated API key to ensure the API that theapplication is authorized to receive the message

5 If both sender and receiver of the message are trusted the message associated withthe beacon will be sent back to the Android Application

42

Figure 12 Message Exchange Using Google Nearby

644 Permissions and requirements

The android manifest is a file that defines the functionality and specifications in an An-droid applicationThe manifest provides fundamental information which the system musthave before running the application The manifest describes the components of the appli-cation(eg activities services etc) and indicate the permissions that an application shouldhave to access the protected parts of an API[18]

43

44

7 Result and Analysis

This chapter goes through the primary result and objectives achieved by this thesis Thegoal was to creat a functioning IoT product that takes the security aspects in regard A testwas applied on every subsystem during the development until reaching the last milestonewhere we had a functioning product

71 Primary Results

The Smart door lock IoT system can successfully authenticate a user and open the doorwhen a nearby beacon is present The user authentication process is handled by theAzure Active Directory where users can easily be created and managed figure 13 BothAuthentication API and DoorAPI are successfully deployed to Azure Cloud and can beaccessed by secure HTTPS requests

Figure 13 Current test members of the Active Directory

The beacon communication between a mobile application and Estimote Beacons ishandled by Googlersquos API and the actual Bluetooth transmission is using the Eddystoneformat Calls to the Google Nearby API has a high success rate and the beacons are fullyregistered in Google Proximity API

Figure 14 Request traffic to Google APIs where Nearby API is blue and Proximity APIis green

Figure 15 The APIrsquos request- and error rate

45

The android application developed follows an easy to use GUI with two main layoutsOne when the user is prompt to login to the authentication service (figure 16) and anotherlayout for when the applications are scanning for beacons (figure 17)

Figure 16 User login UI Figure 17 Login Successful UI

The particle device is connected to the local WiFi of the office and can be called uponusing HTTPS requests The particle device has a long lasting connection and waits forincoming requests

Figure 18 Particle Spark Console displaying various events relative to the specific PhotonDevice

46

72 Discussion

This subchapter presents the security challenges and how we managed to solve the securitygaps from IoT system perspective

721 LAN misstrust

We have two gaps that consider LAN misstrust in our system structure The first one isbetween the particle microcontroller and the local network resembled by the WiFi networkThe second LAN misstrust gap is between our Android application when it tries to connectto the the API specifically(Auth API)

Particle has its own Device Protocol Security for handling a secure transmission betweenthe Photon hardware and the Spark Cloud According to Particle documentation followingis said about the protocol

Communications between the Particle Cloud and each Particle device are en-crypted by default Every device ships with a unique device-specific RSA orElliptic Curve key-pair and has a pinned Cloud public key The device publickey is typically pinned in the cloud during manufacturing but can be updatedlater by an authorized user Strong unique keys and bidirectional pinning helpprevent man-in-the-middle attacks against devices and data [19]

As said the encryption keys used for communication is generated and pinned in themanufacturing process of the Particle product and extends from the scope of WiFi Mean-ing that no key exchange between the Particle Spark cloud and Photon hardware designwill go through the wireless network Making all data transmission through WiFi unde-cryptable for other nodes in the network

There is no concrete way to always make sure that the LAN connection completelysecure as smartphone users are admissible to use whatever network they want to This isproblematic when transmissions include sensitive data (such as user credentials and accesstokens) A better approach than securing the LAN for the smartphone is the secure thetransmission itself by encryption If the transmission is encrypted with HTTPS the trustis moved from the LAN to the certificates provided by the requested server The trustedauthority in this case is then the Azure Cloud Moving the trust from WLAN to theAzure cloud acquires a static more secure solution for the product

Due to particles security protocol and the HTTPS protocol used to send sensitive datawe are assuring that no one can eavesdrop on the data transmission and therefore bothgaps being exposed to LAN misstrust are secured

722 Environment misstrust

Environment mistrust is always present in the part of the system exposed to the physicalenvironment which in this case is the Particle Photon device and the Estimote BeaconsAs mentioned before the environmental mistrust differs significantly from different IoTproduct depending on the system structure and the physical surrounding of the hardwareIn our situation We can categorize environment misstrust into two branches one physicaland the other being technical The physical branch includes attacks in the physical mediumFor instance close range jamming attacks that leads to harm the microcontroller or beaconscausing them to malfunction The solution needed donrsquot have to be technical In fact itcan depend more on how and where the user would place the microcontroller and thebeacons

A simple solution to prevent environmental disruption is to place the product (Beaconsand Photon device) inside the building that is behind the actual door the application

47

is controlling In that way only authorized user has access to the nearby environment ofthe hardware preventing the risk of unwanted attention from other humans with harmfulintentions As the unlocking process relies on wireless communication various of layoutoptions exists A simple rule to follow is to hide the beacon and device as much as possiblefar from the reach of physical intervention

The other technical branch revolves around on the communication with nearby devicesHow can the device establish if a received nearby Bluetooth transmission comes from anauthorized device If the device always trusts the source of a transmission a maliciousdevice could impersonate a trusted source in a try to prompt an unwanted behavior fromthe door lock device To prevent this from happening full control of device authorizationis needed This can only be succeeded with reliable encryption and device authenticationmanagement This is why the Google API was a relevant approach for this product Due tothe Eddystone-EID protocol we can filter out all other beacon and Bluetooth transmissionspolluting the environment The one-time key exchange between beacon and smartphonehappens in another medium so no key exchange will take place in the nearby environmentmaking the system thoroughly secure

723 Application over-privilege

To prevent application over-privilege the work needs to be directed towards two main goalsFirstly the application must be developed in a fashion to prevent other third-party appsto take advantage of it But also the application itself must be built in a way so it doesnot do the same to other applications installed on the same smartphone As multipleapplications can exist and run on the same smartphone responsibility is required by theapplicationrsquos creators Optimally all smartphone application should follow the principleof least privilege

As prying third-party application can hold the ability to monitor the traffic reachingour app it is important that all sensitive data is encrypted Therefore a decision wasmade to encrypt all data sent and received by the application created in this project Thisimplies that third-parties application still can have access to the data although the dataitself is unreadable without the correct decryption key

No sensitive data is stored on the smartphone itself due to the projectrsquos system struc-ture The user database authorization and creation of access tokens are outsourced to thecloud and denote one of the key solutions for this project The usage of cloud computingsaves processing power and increases security as well as the overall integrity of the systemAndroid lacks a trustworthy system to store sensitive data locally since the data can beaccess by a rooted device By moving the authorization process to the cloud no data canbe mined from the applicationAdding a cryptography SHA-1 (Secure Hash Algorithm)fingerprint and connecting it to the API key would restricts the API use only for the au-thorized app which adds an extra level of security Furthermore there is no need to storea copy of the database on every userrsquos smartphone which is generally a bad practice

Principle of least privilege means the practice of restricting access rights for users to bareminimum permission needed to perform their task For forcing the application to follow theprinciple of least privilege some simple actions can be taken Every Android applicationcomes with a unique Manifest This manifest provides various important informationabout the application like the application name activities and services The manifestalso provides different permissions needed for the application to function in the desiredmanner These permissions often revolve around communication or permission for accessdata from various sensors of the smartphone eg Gyroscope reading or permission to accessthe Internet or Bluetooth The application needs the user consent to use some permissionsforcing the awareness of the user for what permissions the application uses This increasesthe transparency of the application as well as decrease the privilege malicious application

48

as the user hopefully reflects why an application would ask for irrelevant permissions Inthe SDL Application user permissions for Bluetooth low energy and Internet are used

A small extra note can be made about the usage of the service component As discussedabove multiple applications need to work together and share the same battery processorand memory in the smartphone By implementing the beacon listening on the service wetake the responsibility by saving a significant amount smartphonersquos resources

724 NoWeak Authentication

As mentioned before authentication is simply the process of detrermining if someone iseligible by comparing the credentials provided by the user against the ones in the databasecontating the authorized users Authentication is the core of our project in security contextWe have three main parts that are responsible for the authentication process of a userThese are being introduced in our system as Auth API Door API and Azure ActiveDirectory The central reason for separating the projects APIs into two unique solutionswas because of the access token flow The Particle device is controlled by a single accesstoken that we need to protect Instead of mixing the userrsquos unique access token withthe particlersquos token the decision of splitting the API was made One explanation to thissystem is that basically you need an access token to obtain the particle access tokenThe particle access token can then be nestled and hidden in the door API in a singleinstance rather than stored and copied in multiple smartphone applications

One reason to use the Azure Active Directory is for its extensive way to handle appli-cation handshakes When an application wantrsquos to access a specific API within Azure ADan authorized and encrypted handshake is required This onetime handshake involves thesigning of the public and private key provided by the Azure Cloud This gives full controlover which resources a specific application can access as well as preventing exterior sourcesfrom accessing the projectrsquos APIs

When it comes to user authorization and generating access token the Azure ActiveDirectory is considered as a well-proven process that many web services rely on

725 Implementation Flaws

It is hard to have a rational discussion about the implementation flaws of the product Asparts of the product are outsourced to other companies such as Microsoft and Googlethere is a possibility these companies have made implementation mistakes in their owncode potentially leading to a breach in security This is one of the potential risks ofoutsourcing functionality to other companies

The iterative test development was mainly motivated to prevent the risk of implemen-tation flaws However this tests can only be applied to a certain extent The system mayalways have some bugs or flaws however these tests may prevent the worst-case scenarios

49

50

8 Conclusion and Future Work

This chapter concludes the work done in this thesis

81 Conclusion

Internet of things is one of the hugest revolutions in the technological field It is the conceptthat describes the idea of connecting everyday physical objects to the internet trying todigitalise it As we mentioned before it is expected to have more than 18 billion devicesconnected to the internet by 2022 The risks we are facing are the security aspects whenconnecting these devices and applications to the internet The problem is that each of thesedevices and applications have it is own security gaps that should be considered making ithard to standardize the the security aspects in all the devices

Understanding the basics principles of IoT architectures is a must when developinga product that is going to interact with the nearby environment The product of thisthesis is a fully functional smart door application This system follows the typical IoTinfrastructure explained in chapter 21 Where the smartphone application works as theuser-centric interaction point The developed APIs can be seen as the delegate-part andthe Bluetooth beacons can be interpreted as the sensors It was important that theproduct followed this typical infrastructure as we wanted our prototype to act and behavelike a common IoT-product

The security implementation of the product gave an overall more robust result Byfollowing these 5 major security fields resulted in a more reliable product where we de-velopers had to think outside the box to fulfill the demands of each field However theproduct lacks some security concerning the functionality of the product Due to auto-matic unlocking there is no comprehensive prevention against unwanted unlocking andRelay attacks However an implementation of this problem area is discussed later inthis chapter under future work

We havenrsquot found any other products on the market that is similar to our solutionThe Bluetooth Beacon solution of this project seems to be unique in the consumer marketfor the smart door lock As the Google Beacon API and Google Messages API is a fairlynew technology it is possible it will exist in the nearby future

82 Ethics Sustainability and Benefits

There is always an ethical risk when storing sensitive data in this case being usernameand password in a database A breach of the system resulting in leakage of user credentialcan lead to gruesome consequences and even legal actions in some existing cases As usertends to reuse email addresses and password for different web based services the risk of auser getting compromised on other services as a direct consequence is possible

When it comes to sustainability the development of offices and housing has received asolid boost by IoT Through connected solutions more and more of the buildingrsquos functionscan now be controlled and optimized based on changing needs Using IoT technologies atthe office and home we no longer need to keep an eye on when the coffee machine needsto be filled or serviced or when the lighting needs to be replaced Control of temperatureand ventilation is done automatically Making energy usage analyzed and streamlined atall times

For the Smart door lock some potential sustainability prospect can be gathered Whendigitalizing a lock the dependency of physical key objects such as keys or cards canpotentially be removed By using smartphones as keychains holding multiple keys at atime recourses otherwise going to produce keys and cards could be saved However it ishard to believe that this in some way could compensate for the ecological footprints caused

51

by the production of smartphones The SDL-product assumes that users already own asmartphone and the sustainability of smartphones is therefore outside the scope of thisproject

This product takes responsibility for preventing electromagnetic pollution and distur-bances by only using industry standard transmission protocols and EMC-marked hardwareThis product must have a high electromagnetic compatibility as the product could be de-ployed in heavily polluted areas such as offices located in densely populated areas Thishas not been researched thoroughly but the developed prototype shows no signs of a lackingelectromagnetic compatibility

By moving as much data processing to the cloud as possible the general power con-sumption of the product is decreased Instead of relying on the batteries of the userrsquossmartphone the power of the cloud is used saving energy recourses as well as lower thewear of the smartphone batteries

83 Risks

There is a substantial risk involved with developing an electronic door lock Locks are aproduct of safety and rely on a great trust between product and user The owner of thelock must feel completely confident that the lock is secure This trust is hard to acquireand very easy to lose

A responsibility lies also on the owner and administrator of the smart door lock Care-less usage of the product can compromise the safety of the people inside the building andalso lead to direct damage the buildingrsquos property

This prototype could also very well malfunction either by an external or internal faultof the system This fault could for example be a loss of internet connection or electricityIn that case some kind of backup functionality should be considered This backup couldimply a still functional traditional lock installed on the door or expanding the functionalityof the prototype making it still functional and secure during a powerinternet outage

In extreme cases such as fire emergencies and other relevant scenarios it is of utmostimportance that the door lock behaves in a predictable way The smart door lock thereforeneed to possess the ability to override its normal behavior allowing people to use the doorfreely in such specific cases

84 Future Work

The IoT system that was developed in this thesis focus on the security approach more thanthe functionality of the system However the main functionality of the system has beendeveloped where the user is able to access the door using the mobile app Some of thefunctionality that this system need to be further developed is to make it deployable for agroup of users

Even though the system has a high cohesion within its component it lacks the abilityto handle some alternative workflows The system can control the main use-case but cansometimes be unresponsive because of missing error callbacks It would be reasonable toincrease the amount of feedback the system gives to both users and administrators so thatthe product appears more trustworthy and is easier to troubleshoot

An implementation against relay attacks and unintentional locking should also be over-seen Prevention of relay attacks could be solved by introducing GPS coordinates as a vitalelement One solution could be to force the mobile application to check if the smartphonecoordinates closely match the coordinates of the deployed beacon In that way the beaconwill only request to open the door when it is physically present the system and thereforemaking relay attacks even more difficult

52

Unintentional unlocking could be solved with a similar solution using GPS technologyYou could implement the system in a way that the user needs to leave the office with acertain distance before the application asks for unlocking again preventing the risk of theapplication resending requests when the user is located inside the office Another simplerapproach could be to install a simple button next to the door prompting the door to openif both a userrsquos smartphone is nearby and the button is pressed However this solution isnot ideal as a non-user could wait outside the door until a person inside the building walksby

53

References

[1] Ericsson AB Iot security white paper httpswwwericssoncomassetslocalpublicationswhite-paperswp-iot-security-february-2017pdf Ac-cessed 2017

[2] Jie Lin Wei Yu Nan Zhang Xinyu Yang Hanlin Zhang and Wei Zhao A surveyon internet of things Architecture enabling technologies security and privacy andapplications Internet of Things Journal IEEE 4(5)1125ndash1142 October 2017

[3] Kewei Sha Ranadheer Errabelly Wei Wei T Andrew Yang and Zhiwei WangEdgesec Design of an edge layer security service to enhance iot security In Fogand Edge Computing (ICFEC) 2017 IEEE 1st International Conference on pages81ndash88 IEEE 2017

[4] Grant Ho Derek Leung Pratyush Mishra Ashkan Hosseini Dawn Song and DavidWagner Smart locks Lessons for securing commodity internet of things devicesMasterrsquos thesis University of California Berkeley 2016

[5] Nan Zhang Soteris Demetriou Xianghang Mi Wenrui Diao Kan Yuan PeiyuanZong Feng Qian XiaoFeng Wang Kai Chen Yuan Tian Carl A Gunter KehuanZhang Patrick Tague and Yue-Hsun Lin Understanding iot security through thedata crystal ball Where we are now and where we are going to be httpsarxivorgabs170309809 2017

[6] Abdillahi Hassan Adnan Mohamed Abdirazak ABM Shamsuzzaman Sadi Tow-fique Anam Sazid Zaman Khan and Mohammed Mahmudur Rahman A compar-ative study of wlan security protocols Wpa wpa2 httpieeexploreieeeorgdocument7506822 2015

[7] Indiana University What is the principle of least privilege httpskbiuedudamsv 2017

[8] A Perrig et al In The Tesla Broadcast Authentication Protocol CryptoByte vol 5pages 2ndash13

[9] George Hatzivasilis Ioannis Papaefstathiou Konstantinos Fysarakis and IoannisAskoxylakis Secroute 2end-to-end secure communications for wireless ad-hoc net-works In Computers and Communications (ISCC) 2017 IEEE Symposium on pages558ndash563 IEEE 2017

[10] Earlence Fernandes Justin Paupore Amir Rahmati Daniel Simionato Mauro Contiand Atul Prakash Flowfence Practical data protection for emerging iot applicationframeworks In 25th USENIX Security Symposium (USENIX Security 16) pages 531ndash548 Austin TX 2016 USENIX Association

[11] Yan Michalevsky Suman Nath and Jie Liu Mashable Mobile applications of se-cret handshakes over bluetooth le In Proceedings of the 22nd Annual InternationalConference on Mobile Computing and Networking pages 387ndash400 ACM 2016

[12] Aurelien Francillon Boris Danev and Srdjan Capkun Relay attacks on passive keylessentry and start systems in modern cars httpseprintiacrorg2010332pdf

[13] Torry Harris Cloud computing servicesmdasha comparison International Journal ofComputer and Information Systems 31ndash18 2010

54

[14] Google inc Eddystone format httpsdevelopersgooglecombeaconseddystone

[15] Google inc Eddystone ephemeral identifier httpsdevelopersgooglecombeaconseddystone-eid

[16] Sitepoint tutorials What is a rest api httpswwwsitepointcomdevelopers-rest-api

[17] Tutorialspoint Android architectural layers httpswwwtutorialspointcomandroidandroid_architecturehtm

[18] Android developers Andriod manifest httpsdeveloperandroidcomguidetopicsmanifestmanifest-introhtml

[19] Particle IO Security check list of internet of things Security check for iot devices37ndash9 2017

55

TRITA-EECS-EX-20183

wwwkthse

Page 23: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 24: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 25: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 26: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 27: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 28: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 29: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 30: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 31: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 32: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 33: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 34: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 35: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 36: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 37: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 38: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 39: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 40: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 41: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 42: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 43: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 44: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 45: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 46: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 47: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 48: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 49: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 50: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 51: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 52: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 53: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 54: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 55: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice
Page 56: IoT Security Applied on a Smart Door Lock Application1216681/FULLTEXT01.pdfing a smart door lock for making it connected to the internet and able to recognize employeesthatworkintheoffice