• No results found

Modular embedded system for electronic code locks

N/A
N/A
Protected

Academic year: 2021

Share "Modular embedded system for electronic code locks"

Copied!
27
0
0

Loading.... (view fulltext now)

Full text

(1)

INOM

EXAMENSARBETE

INFORMATIONSTEKNIK,

AVANCERAD NIVÅ, 30 HP

,

STOCKHOLM SVERIGE 2017

Modular embedded system

for electronic code locks

JIM THEORELL

KTH

(2)

Modular embedded system for electronic code

locks

Jim Theorell, KTH, Embedded systems

Abstract—This thesis aims to build a modular embedded system for a set of pre defined constrains, including a code algorithm for temporary access codes. The system are to be physically adapted for electronic code locks and foremost a pre-existing lock. The thesis provides a set of tools that will be used for creating the system. Furthermore the choice of components and the design decisions are accounted for. The software of the system is discussed along with the choosen security solutions. Lastly it discusses the problems with product certifications that this kind of system has to face.

Index Terms—Modular embedded systems, Bluetooth, electronic code locks.

F

• Handler Qiang Chen, KTH, EKT KOMPONENTER OCH KRETSAR.

(3)

L

IST OF

A

CRONYMS AND

A

BBREVIATIONS

This document requires readers to be familiar with terms and concepts of embedded systems and bluetooth low energy. Below is a list of common abbreviations.

mTAC Mobile Temporary Access Codes, a patented technology from Telkey. Used to create temporary codes.

PCB Printed Circuit Board

NFC Near-field communication

RTC Real Time Clock. Please observe that in many embedded situations the may refer to Real Time Counter. But in the scope of this thesis, RTC only refers to Real Time Clock unless otherwise specified.

SDK Software Development Kit

MCU Microcontroller unit

IC Integrated circuit

FDS Flash Data Storage

(4)

C

ONTENTS 1 Introduction 5 1.1 Organisation. . . 5 1.2 Telkey Solutions. . . 5 2 Background 5 2.1 mTAC . . . 5 2.2 Modular solution . . . 5 2.3 Goals . . . 6 2.4 Immediate application . . . 6 2.5 System overview . . . 6 2.5.1 Project scope . . . 6 2.5.2 Thesis scope . . . 6 2.6 Limitations. . . 6 2.6.1 Size . . . 6 2.6.2 Nordic . . . 6 2.6.3 Interface . . . 7 2.6.4 Debug . . . 7 2.6.5 Fixating. . . 7 2.6.6 Voltage . . . 7 2.6.7 Power. . . 7 2.6.8 RTC . . . 7 2.6.9 Security. . . 7 2.7 Previous work. . . 7 3 Method 8 3.1 Requirement definition . . . 8 3.2 Hardware implementation . . . 8

3.3 Software requirement definition . . . 8

3.4 Software implementation. . . 8 3.5 Development tools . . . 8 3.5.1 nRF52 development kit . . . 8 3.5.2 J-Link . . . 8 3.5.3 Debug . . . 8 3.5.4 Environment . . . 8 3.6 CAD . . . 9 3.7 Manufacturing. . . 9 4 Results 10 4.1 Motherboard. . . 10 4.1.1 Components . . . 10 4.1.2 Schematics . . . 10 4.1.3 PCB layout . . . 10 4.2 Serial protocol . . . 11 4.3 Enviroment Setup. . . 11 4.3.1 Makefile . . . 11 4.3.2 Logging. . . 12 4.3.3 Error handling . . . 12 4.4 Software . . . 12 4.4.1 NRF platform . . . 12 4.4.2 Main program . . . 12 4.4.3 BLE service. . . 13 4.4.4 mTAC library . . . 14 4.4.5 RTC library. . . 15 4.5 Security . . . 16 4.6 Lock security . . . 16

4.6.1 BLE pairing and bonding . . . 16

4.6.2 Vulnerabilities . . . 16

(5)

5 Discussion 19 5.1 PCB design considerations . . . 19 5.2 Certifications . . . 19 5.3 CE and modules. . . 19 5.4 System functionality . . . 20 5.5 Conclusion. . . 20

Appendix A: Schematic, prototype 1 21 Appendix B: Error handling 22 Appendix C: PCB 23 C.1 Front PCB . . . 23

C.2 Back PCB. . . 24

(6)

1

I

NTRODUCTION

This section introduces the reader to the persons and organ-isations involved.

1.1 Organisation

This project is organised the following way: TABLE 1

Organisation

Jim Theorell* Student/Developer Jan S ¨oderlund Company representative

Qiang Chen KTH handler

Hannu Tenhunen KTH examiner

* Please note that Jim Theorell, the author, is also an employee of Telkey Solutions AB, the client for this project. When the author uses the pronoun ”our” or ”we” it is referred to Telkey.

1.2 Telkey Solutions

Telkey Solutions develops and sells access solutions based on our patented technology called mTACTM (Mobile Tem-porary Access Codes). The client creates virtual time keys in the cloud that are used to open areas - homes, cottages, offices, service areas, lockers, sports facilities. We don’t develop our own locks but rather software and embedded systems.

2

B

ACKGROUND

This section introduces the reader to background and moti-vation behind the project.

2.1 mTAC

The main idea behind mTAC is to provide a solution for opening locks without connecting them to the internet or local gateway, while still being able to dynamically set the valid time for every given code.

mTAC works on the same basic principle as most bank-ing systems utilize. When joinbank-ing a bank with online ser-vices, you normally get a personal device sent home where you can generate single use codes for login in or signing documents. The personal device contains a set of secret numbers that only this device and the bank knows. When logging in, the bank asks you to write a number in your personal device. The personal device will then display a second number. This number represent a secret number that you enter on the web page of the bank. This proves that you have access to your personal device, since only the bank and you have a set of these secret numbers.

mTAC however reverses this and makes it one step. As in the bank case, the lock(personal device) and the Telkey server(bank), share a set of secrets. But in this case the Telkey server generates a 18 digit code. In this code the secret is stored. And instead of writing a number in your personal device to determine which secret to use, the actual time is used.

So to put every thing together: 18 digits is produced by the server. Embedded is the time that this particular code should be valid and the shared secret. When the user enters this code in the lock, the time is extracted. If the secret then matches the given time, this proves that someone with access to the shared secrets generated the code. If the time contained in the code is the actual time, the door is opened. If the time is in the future, the code is whitelisted. This means that the last 5 digits of the code will automatically start to work as an opening code when the time is right.

This however is a simplification of the system. The actual implementation contains additional encryption to increase entropy. In reality the shared secret is actually several secrets to prevent manipulation of codes to change their validity.

The next generation of mTAC codes could potentially contain hundreds of digits since it may be delivered through a bluetooth connection. This will enable for additional in-formation inside a code and potentially increase the time resolution and security.

mTAC

code

Fig. 1. How mTAC(TM) works: The server and the lock alone contain a set of common secrets. The secret associated with a certain time is embedded in the code. When the user then tries to open the lock for any specific time the secret have to match, thereby proving that a user authorised by the server generated the code.

2.2 Modular solution

With customers requesting the functionality of mTAC for their specific situation, the need for new embedded systems constantly arises. These systems almost never have the same requirements as the others. This means that every new systems demands extensive development and prototyping time.

If a modular solution could be made instead, this could potentially mean that only a small part of the system have to be developed to extend the functionality. If the development time can be shortened, the time to market may be reduced. Shorter development time also means an increased number of possible projects for potential profit.

(7)

Main Board Communication Communication Fixation Fixation Communication Debug Modules Power Case External systems

Fig. 2.A modular solution. By designing a system that uses mod-ules, the development time for new systems may be reduced.

2.3 Goals

To produce an embedded system for a battery powered door lock. The system should consist of a motherboard that can communicate with one or more other modules that adds functionality and/or interface options.

2.4 Immediate application

The first application of the new system has already been decided. It will be integrated in an electronic code lock from the company EXMA1. The system will communicate with

the locks existing circuitry. A protocol have been made that will enable information and commands to be transferred by serial communication. The system will be made as versatile as possible while still remaining fully compatible with this lock.

2.5 System overview

2.5.1 Project scope

The project is a complete suite for managing users, per-missions and security for different locks. The top level is a cloud service where locks can be registered to organizations and users permitted to access certain locks. This can partly be done through an mobile application that Telkey will provide. However another option is to use the API and hook right in to the server. This is probably the most common solution since this allows the customer to integrate the code generation features in their own system. Whatever path is chosen, there will be a backend library that is responsible for communicating with the lock. This will greatly simplify the task of implementing 3:d party services and also ensure that the security between lock and phone remain uncom-promised.

1. The lock is called ”Duo” and can be found on the product page: http://exma.se/produkter/ Server API Smartphone Backend/ Library Frontend/ Telkey app Frontend/ 3:d party app Telkey cloud service 3:d party service Telkey server BLE connection

Fig. 3.Project overview. The blue parts are under Telkeys re-sponsibility, which means customers have a secure delivery system of codes. The red part is the alternative route where the customer have e.g. their own booking system.

2.5.2 Thesis scope

This thesis will be a part of the bigger project with the border being the bluetooth communication and serial communica-tion with the lock. Therefore it entails pcb design, security, programming, communication protocols, physical form and modules. The project scope can be view in fig3

2.6 Limitations

This is a list of the limitations the system are subject to. The list contains both functional and non-functional require-ments.

2.6.1 Size

For the system to fit as many applications as possible. It is preferable to make the pcb small. A small PCB will take longer to develop and provide several difficulties in design decisions. But for the added flexibility this is an investment. 2.6.2 Nordic

(8)

with 512kB flash + 64kB RAM. It has an embedded 2.4GHz transceiver that supports Bluetooth low energy as well as NFC.

2.6.3 Interface

A serial protocol has been specified to communicate be-tween the motherboard and the lock. The protocol includes a set of commands and status messages. Because of a non-disclosure agreement, the details of the protocol will not be presented in this report.

2.6.4 Debug

Because of the modularity of the system, good debugging capabilities are required. Particularly so on the mother board, since the code on the motherboard will have to account for any new module that may be created in the future. Therefore a dedicated debug solution will have to be present on finished product. This with as little impact on performance and size as possible.

2.6.5 Fixating

For attaching the PCB to container, some kind of fixation points have to be created. Since the distances will vary greatly for every lock, this will have to be solved with plastic spacers that can be made for the situation. Additionally the modules must be able to attach to each other and the mother board. Preferably this can be solved in a way that it may be put together in several different configurations for different purposes. For example attached in a long line or stacked on top of each other depending on available space.

2.6.6 Voltage

The system will be required to work with voltages between 3-6VDC.

2.6.7 Power

The system should not have a peak current consumption exceeding what may be safely discharged from a normal AA battery, preferably even a coin cell battery. However the average consumption will have to be very low. The functional requirement will be that during normal use, 5 openings per day, the battery will last for at least a year when powered with 4 consumer grade AA batteries. 2.6.8 RTC

For mTAC to work, an accurate real time clock is needed. The clock will need to have a high accuracy over long periods of time and despite varying temperatures.

2.6.9 Security

Since the mTAC codes can be reused during the speci-fied time interval, it is necessary to prevent anyone from listening to the bluetooth communication. The goal is to strengthen the bluetooth security until the physical durabil-ity of the lock is the weak point. Meaning it should require less effort to break an individual lock by force then to hack the bluetooth connection.

2.7 Previous work

The spectrum of modular systems that have been previously created can be placed based on the premise of the specific project. Firstly we have the consideration between mission efficiency and application flexibility. Where a specialised system naturally performs best, however a generalised sys-tem is flexible for reuse. Another consideration for the system designers is the form factor. Some projects just do not allow for any flexibility with the physical attributes.

One could therefore theorize that many of the systems developed will remain proprietary of the organisation/com-pany that produced it. This in turn leads to the amount of research in the area being limited. The systems available on the market are made for application flexibility with limited focus on mission efficiency and especially lacking in the physical form. An example of this is the Waspmote2. The Waspmote system offers several different connectivity options for both wired and radio communication. They also provide multiple different sensor modules. However the high price and large size makes it unsuitable for this thesis project.

A team from Sandia National Lab in Livermore, CA, USA, have used another approach in their MASS project: ”MASS is a novel design approach achieving both mission efficiency and application flexibility in a single system by decoupling system management from in-system data fu-sion and signal processing. The key to achieving this is a modular, multiprocessor hardware architecture operating under an intelligent distributed software control. Instead of relying on the traditional flexible node architecture in which resource control is centralized on a single high power processor, each resource in a MASS node is built into phys-ically separable modules with supporting resource specific processors.” [1, p. 394]

However what MASS has in common with most of the different sensor networks developed during the last 15 years, they all tries to fit too many applications. Thereby they fail to be mission effective and/or costs to much.

(9)

3

M

ETHOD

This section describes the different steps needed to complete the project.

3.1 Requirement definition

The first step will be to turn all the non-functional require-ments, mentioned in 2.6 (Limitations), into functional re-quirements. In the first iteration only requirements affecting hardware have to be considered. These new requirements is valid for the current prototype step and is subject to be changed later.

3.2 Hardware implementation

Based on the functional requirements an embedded system is produced. The following tasks are performed:

1) Component selection 2) Electrical schematics 3) PCB design

4) Manufacturing 5) Assembly

3.3 Software requirement definition

After the hardware prototype is done, another iteration of requirement elicitation may be done. This time with focus on the software.

3.4 Software implementation

3.5 Development tools

3.5.1 nRF52 development kit

Fig. 4.The development kit for the nRF52832 chip. Built in an-tenna and j-link programmer. Arduino compatible headers. Pic-ture fromhttps://developer.mbed.org/media/uploads/andrzej z krakowa/nrf52 dk pinout armmbed enabled v2.png

To start off the project, the nRF52 development kit will be used. It contains a nRF52832 chip with a built in antenna. It also contains a debug and programmer unit with j-link

capabilities. The pin headers are Arduino compatible, which means that many shields made for the Arduino platform will work. Additionally, there are several leds and buttons. Included with the kit is a NFC antenna that is ready to be connected.

3.5.2 J-Link

For debugging and programming MCU:s on the prototypes, a J-Link base will be used. It supports several debug options but for this project the 6-pin SWD (Serial Wire Debug) will be used exclusively. SWD is a standard debug method from ARM, normally it is used with a 10-pin header, which is already lower than many other debug alternatives. This project however will only use 6 pins and a special header, which will be presented in section 4.1.1 (Components). SWD is used for programming bootloaders, uploading the programs and debugging.

3.5.3 Debug

The J-Link debugger comes with a free program called Ozone. Ozone is a full-featured graphical debugger for embedded applications. However since the developed pro-gram contains BLE elements, it is not always possible to use breakpoint debugging. If you pause the processor, the timing critical bluetooth stack fails and the communication can not be resumed. Additionally the device on the other end of the communication will assume that the connection was broken and issue a timeout error.

Segger, the company behind J-Link, provides another function called RTT (Real Time Terminal). This is a fast way to print arbitrary data to the connected PC. It uses a structure in the target memory to manage reads and writes in the terminal making it extremely fast. Nordics SDK (Software Development Kit) have a logging module that, as default, uses printf. With RTT included in the project it is possible to switch the logging module to instead use RTT. 3.5.4 Environment

The source code will be written and compiled on a windows 10 computer. All examples by Nordic Semiconductor have a Keil uVision project file included. This means that they are ready to be compiled and deployed on the development board without significant effort. Keil is a capable devel-opment environment, however the evaluation version has a critical limitation: Programs that generate more than 32 Kbytes of code and data will not compile, assemble, or link3.

Naturally it is not possible to develop under those con-ditions and unfortunately the commercial versions are far to expensive for a startup company. Therefore this project will be using the gcc toolchain for ARM. Fortunately Nordic pro-vides excellent makefiles for building projects. This includes building all SDK components needed along your own code. For editing code, Sublime 3 will be used. It is an ded-icated text editor with a great selection of plugins. It also contains scripting abilities.

(10)

3.6 CAD

For designing the PCB, the open source Electronics Design Automation (EDA) Suite KiCad will be used. It contains tools for the entire process of creating circuit boards, every thing from schematic to gerber files. It is a powerful tool that can be a little unrefined in some parts, probably due to the nature of its open source development. There are a bit of a learning curve to the software, but this is something that can be expected from commercial EDAs as well.

KiCad has several different parts that are used to pro-duce a result. The basic work flow will follow this pattern

Schematics Schematics are created in the module called

Eeschema. The users starts with a blank schematic and need to add components. There are several components in the built in libraries. But you will probably have to create most by yourself. This is done in the Library module, specifically the part library editor. Besides creating the visual symbol for the schematics, pins are added and optionally configured for specific use, such as input, open or power.

Back in Eeschema all components are wired as desired. Then all components are annotated and a netlist is generated. The netlist will be read by the pcb module in a later step.

Footprints Before starting with the PCB layout all

compo-nents have to be associated with a footprint. KiCad features a full fledged footprint editor. Footprints may be created from scratch and equipped with pads, vias and silkscreen. When all components are associated with a footprint we can move to next step.

PCB This module is called Pcbnew. It generates a ratsnest with all components based on the netlist generated by Eeschema. There are no limitations of the amount of layers or board size that can be used, which is the case in for example Eagle CAD. KiCad features a powerful interactive router. The router can be used in something called ”shove mode”, that lets already made traces being ”shoved” around by the one you are currently dragging.

When satisfied with the wires, fill layers can be added. And of course silkscreen, board dimensions and holes can be created. Lastly KiCad exports to various formats including gerber files.

3.7 Manufacturing

During the development process, the PCBs will be ordered from a Swedish fabrication house called Cogra Pro4. They

provide a fast and reliable pre prototype service. Assembly will be done manually and soldering in a small table top reflow oven.

(11)

4

R

ESULTS

4.1 Motherboard

4.1.1 Components

The following components have been chosen:

MCU The project limitations state that an nRF52832 should be used. However there are still choices to be made. Because the nRF52832 MCU needs an antenna to work. There are available resources from Nordic aiding an-tenna designs. But it is still an considerate effort since the antenna has to be tuned if it is to come near full possible range. Besides the additional time and effort, another downside is the certification from Blue-tooth SIG (Special Interest Group). If you design your own antenna, it have to be certified by a Bluetooth Qualification Test Facility approved by Bluetooth SIG. The other option is to buy a module with MCU and antenna integrated. The unit price for MCU+antenna is obvious lower that that of a module. The chosen module EYSHCNZXZ by TAIYO YUDEN costs about 100 SEK, compared to only 25 SEK for the MCU. However with development, components and qualifi-cation costs, some 4000 locks has to be produced before it breaks even. Additionally the development time is significantly increased.

The EYSHCNZXZ module has, besides the MCU and antenna, some additional hardware. Firstly it contains an DC/DC LC filter that is required by the MCU to operate the internal DC/DC converter, see chapter 18 in the nRF52832 datasheet5. Additionally two crystal oscillators, 32 MHz and 32 KHz, are included.

RTC Most real time clocks on the market lacks what is called an Temperature Controlled Crystal oscillator (TCXO). A TCXO can compensate for different temper-ature conditions, providing a accurate frequency. There are a few IC:s on the market that can get below ±4ppm (parts per million) in deviation. 3.8ppm is equivalent to the clock deviating 13 seconds per month. The chosen version, Epson RX8900CE UA3, has an accuracy of ±1.9ppm in conditions from 0 to 50◦C and ±3.4ppm in -40 to 85◦C6. The noteworthy about this

particu-lar model and version is that it comes in a custom package. This package only has a 3.2x2.5mm footprint, compared to the alternate version (RX8900SA), which is a 10.1x7.4mm 14-pin SOP.

Voltage Regulator The voltage regulator is also chosen for

the small package size and low quiescent power. It is a XC6218P302HR-G from Torex Semiconductor7. It has a

fixed output of 3V and can supply 200 mA.

Module connector For connecting the modules, two things

are considered: Flexibility and size. The connector foot-print must be small to fit the PCB and the solution must support various arrangements for the modules. The so-lution is an FFC (Flat Flexible Cable). The molex version used has a pitch of 0.5 mm which is enough to handle the low power needed for the modules. The connector 5.http://infocenter.nordicsemi.com/pdf/nRF52832 PS v1.3.pdf 6. See datasheet page 3: http://www5.epsondevice.com/en/ products/i2c/rx8900ce.html

7.http://www.mouser.se/Search/ProductDetail.aspx?R=

XC6218P302HR-Gvirtualkey68650000virtualkey865-XC6218P302HR-G

is also from Molex8 and is a ZIF (Zero Insertion Force)

model. That means it has an actuator that is flipped down when the cable is in right position, thereby fixing the cable in place. The connector was chosen from a selection of models based on three conditions: The force required to dislodge the locked cable, footprint size and price.

Interface connector The interface connector is the same

models as the module connector only with a greater pitch of 1mm.

Debug header The debug port is a 6-pin SWD interface.

However it is a special header solution developed by the company Tag-Connect. This model, TC2030-CTX-NL, as can be seen in fig5, has six pogo pins and three fixation pins. A pogo pin is a spring loaded connector that retract when pushed against the PCB. This gives all six pins a good connection to the board. The only requirements on the board is six 0.8 mm round pads and three 1 mm holes. This saves space and money since the cost of the debug header per PCB is almost negligible. There is a optional clip that can be put under the board to keep the connector in place for extended time, very useful during debugging.

Fig. 5. The Tag-connect TC2030-CTX-NL. Picture source:http://www. tag-connect.com/Materials/TC2030 NL connector.jpg

4.1.2 Schematics

Schematics are listed in AppendixA. 4.1.3 PCB layout

There are several parameters that have to be analysed when designing the PCB. The component placements impact on the total size of the PCB being most limiting factor. The first and foremost constraint when designing the layout is the MCU/ bluetooth module. It has a built in antenna that needs to be placed with care to maximize signal strength. The modules antenna needs to be placed in a metal exclusion zone. Meaning that there can not be any copper in any plane

(12)

underneath the antenna and 5 millimetres to the sides. The suggested placement methods from the datasheet can be seen in figure6.

Fig. 6. The recommended placement options for TAIYO YUDEN EYSHCNZXZ BLE module. The green area is an metal exclusion zone. Datasheet from http://www.yuden.co.jp/wireless module/document/datareport2/en/TY BLE EYSHCNZXZ DataReport V1 4 20170630E.pdf

The second and the third largest components are the two ZIF connectors. They are therefore placed on the opposite side of the board to minimize PCB size. Since they are both of the type with horizontally attached cables, they need to face away from each other to avoid crossing the cables. For the debug port (Connector P1) the trouble is that it needs three holes that goes though the PCB. Additionally it needs a ”clip” on the bottom side to keep it in place during debug session. This can of course be skipped and the connector may be pressed to the PCB temporary. But since this project is supposed to be modular and the debug post is a essential part of that, it was decided the clip is needed. On the top side the connector also requires some space. Picture renditions of both sides of the layout is available in appendices C.1 and C.2. Rather than making the card long and thin, the connector was placed parallel to the rectangular MCU module. Because connector P3 is slightly larger than P2, the debug port have to be placed in one corner of the square. The only free space left is the top left corner on the bottom side, where the last big component has to be placed, the RTC.

The Voltage regulator (U1) is placed between connectors P2 and P3 as close to the external power supply line as possible. Both decoupling capacitors are placed adjacent to the regulator giving improved stability in the circuit. the MCU itself has double decoupling with the small value located on the bottom side and the bigger one on the top layer just on the other side of the PCB from the VCC NRF pin. Same principle applies to the capacitor for the RTC, where there is no space on the bottom layer. There are no need for resistors on the I2C lines since there are internal Pull up/down resistors connected to every MCU pin.

There are a pair of pads and capacitors on the top side of the bottom layer. These are for connecting an NFC antenna if the need should arise in the future.

Lastly there are two 1.3 mm holes 13.5 mm apart at the top. These are for fixating the PCB inside a case or attaching another module.

4.2 Serial protocol

To communicate with the lock, a serial protocol have been specified. The aim of the protocol is not necessary to only fit the purposes of this project but to be a general interface that the lock can use for multiple situations. Telkey is the reason EXMA, the lock manufacturer, installs a 3d-party interface but does not have exclusive rights to buy and integrate with the lock.

4.3 Enviroment Setup

4.3.1 Makefile

Several steps have been made to ease development of the board. This is important not only to decrease development time but to enable for new modules to be implemented on top of the old code. It is also important to ensure that the project remains comprehensive and easy to pick up for new developers.

This project uses the SDK version 13.0.0. It is preconfig-ured to find the SDK folder on the same level as the project folder. If this is not the case it will have to be changed in the makefile.

Several things have been changed in the makefile. Firstly all SDK libraries need to be manually added with both source and header file. One such example is the Segger RTT: The SRC FILES variable has to be appended with:

1 $ (SDK ROOT) / e x t e r n a l / s e g g e r r t t / SEGGER RTT . c \

and the INC FOLDERS with:

1 $ (SDK ROOT) / e x t e r n a l / s e g g e r r t t \

With the services and libraries created specifically for this project, a slightly different approach is used. For source files these lines were added:

1 $ ( PROJ DIR ) $ ( wildcard l i b s /∗∗/∗. c ) \ 2 $ ( PROJ DIR ) $ ( wildcard s e r v i c e s / ∗ . c ) \ and header files:

1 $ ( PROJ DIR ) $ ( wildcard l i b s /∗∗/) \ 2 $ ( PROJ DIR ) $/ s e r v i c e s / \

This enables any library folders that is placed in the /libs / to be automatically compiled. This also works for any service files placed in /services.

Additionally another target has been added for make: flash all . This is for making a chip operational disregarding its previous state of programming. The target is erased, softdevice is flashed, mTAC hex file is programmed and device is reset.

(13)

SRecord collection9. With the following command, a file can

be configured to start at 0x00012345 in memory. More about memory management in section4.4.4 (mTAC library). 1 s r e c c a t INPUT . bin −b i n a r y −o f f s e t 0

x00012345 −o OUTPUT. hex − i n t e l

The offset is needed since the mTAC data would otherwise overwrite the application that is automatically placed in the lower region of the flash memory.

The make targets have then been added to the .sublime-project file to enable them to be executed from the menu or with keyboard shortcuts within sublime.

4.3.2 Logging

Nordic offers a logging module that is used by SDK mod-ules and may also be included in the application code. It provides four levels of severity: ERROR, WARNING, INFO, and DEBUG. The printout is formatted with the printf style. Default settings for the logger module is to use UART as back end. But it also offers the option to use SEGGER RTT10 which greatly increases the speed of the printout.

This is important since the softdevice is highly sensitive to interruptions because of the timings required during radio communication. To enable RTT, the following line have to be set to 1:

1 # d e f i n e NRF LOG BACKEND SERIAL USES RTT 1 and of course we want to turn off UART:

1 # d e f i n e NRF LOG BACKEND SERIAL USES UART 0

4.3.3 Error handling

Nordic semi has an error code system based on 32-bit numbers. All SDK functions return an error code that is 0 if successful. Since current and probably future libraries created will call SDK functions internally, these error codes are simply passed on to the application. The SDK then offers an error module that can be called for every new error code. It may be called with:

1 APP ERROR CHECK( e r r c o d e ) ;

This will eventually call a weak function that has been overridden in the main application with the function that can be found inB (Appendix 4

Error handling). The function will restart the MCU in case

no DEBUB flag is defined at compilation. This is necessary for the product to remain useful in case an error occurs. However if debug is activated it will print the line number, file and error code that caused the error, and then go in to an infinite loop. To get this information is immensely helpful since it is in most cases not possible to step-by-step debug bluetooth applications. 9.http://srecord.sourceforge.net/ 10.https://www.segger.com/products/debug-probes/j-link/ technology/real-time-transfer/general-information/ 4.4 Software 4.4.1 NRF platform

Nordic Semiconductor uses something they call a SoftDe-vice. The main purpose of the SoftDevice is to implement the BLE stack implemented by Nordic Semiconductor. Nordic describes the SoftDevice like this: ”A SoftDevice is a wireless protocol stack library for building System on Chip (SoC) solutions. SoftDevices are precompiled into a binary image and functionally verified according to the wireless protocol specification, so that all you have to think about is cre-ating the application. The unique hardware and software framework provide run-time memory protection, thread safety, and deterministic real-time behavior. The Application Programming Interface (API) is declared in header files for the C programming language. These characteristics make the interface similar to a hardware driver abstraction where device services are provided to the application, in this case, a complete wireless protocol.” 11 It is loaded in to flash

memory of the MCU, however it is not necessary to use the SoftDevice if BLE support is not needed.

The SoftDevice is not dependent on any operating sys-tem, even though any RTOS may be used, but uses event-driven operations. Many SDK libraries offer both asyn-chronous and synasyn-chronous versions of every function. The main application for this project utilizes event driven op-eration as much as possible. This reduces delays between parts of the application and minimizes the risk for dead-locks. Those operations that require periodical attention is triggered by events generated from timers.

There are several different priority levels among inter-rupts, where all SoftDevice events regarding bluetooth have precedence. However from a practical point of view there are only two: Interrupt or normal context. Normal context is what happens in the main function. Interrupt is whenever an event occurs. It is sometimes necessary to move execution from interrupt to normal context. The move is then done by the scheduler module. In interrupt context, tasks that needs to be performed in normal context are queued with app_sched_event_put(). The scheduler gets request for functions that needs to be run and then executes them, according to priority, when execution returns to normal context.

4.4.2 Main program

The main function consists of two parts: Initializations and a main loop. The main loop is what the normal context will run indefinitely after initializations are done. Therefore it only contains two things:

app sched execute() This is the function that begins

exe-cution of all the functions that have been sent to the scheduler. Since the main function itself do not give anything to the scheduler, every task in the queue is from an interrupt context. These sources are either BLE, UART or timer event.

power manage() Puts the MCU in a low power state until

it detects an event.

The following initializations is done:

(14)

log init() Initializes the logging module.

timers init() Initializes the timer module and creates two

timers. The first one for checking the battery status. The second is used for time-out in the serial communication.

scheduler init() Initializes the scheduler module.

ble stack init() Initializes the SoftDevice and all required

settings. Regardless of what functionality a BLE de-vice has, it will still have to define a GAP, Generic Access Profile. This sets up the most basic functions such as advertisement and role. Some of these set-ting are done here. Tweaking the setset-tings of these parameters are sometimes done by changing param-eters in sdk config.h. This function is mostly boil-erplate code that is necessary to have for normal bluetooth operation. However some really important things are done in this function. Firstly, the call to softdevice_app_ram_start_get() returns the memory address that where the main applications ram space should start. Since the SoftDevice has its own memory space for integrity reasons, this region is sep-arated from the user ram. Since the RAM requirement of the SoftDevice changes with versions and settings, the border between RAM spaces can be moved by editing the linker file. For example this projects linker file contains the declaration:

1 MEMORY 2 {

3 FLASH( rx ) : ORIGIN=0 x1f000 ,LENGTH=0 x61000

4 RAM( rwx ) : ORIGIN=0 x200025f8 ,LENGTH=0 xda08

5 }

The first line is to make sure the SoftDevice get a reserved space in flash memory. The second in RAM. RAM adresses start at 0x20000000 which means that we reserve 0x25f8 bytes with the ORIGIN variable. LENGTH is the total RAM (64kB in this model) sub-tracted with SoftDevice usage. The application will print the required RAM if the logging level is set to debug.

After all settings is configured, the SoftDevice is started and event handlers are registered.

gap params init() Configures the rest of the GAP

parame-ters. The setting used are changed with defines at the top of file. For example the name of the device: 1 # d e f i n e DEVICE NAME ” Telkey Lock”

gatt init() Initializing the GATT module.

advertising init() Initializing the advertising. This function

determines the content and form of the broadcasted packet that other devices see when scanning.

services init() This is where all services are configured and

registered with the softdevice. The first one, Battery service, is a standard service defined by Bluetooth SIG. This means that Nordic have an implementation ready. It also means that it has a special short UUID so that every device connecting to the lock knows what this service is. The second service is a custom service for unlocking the lock. All steps involved will be explained in section4.4.3 (BLE service).

conn params init() Configures the behaviour of

estab-lished connections.

rtc init() Initializes the RTC for use. The procedure will be

explained in section4.4.5 (RTC library).

serial com init() Initializes the serial module and creates a

fifo queue that is used to store message data.

fds app init() Initializes the FDS (Flash Data Storage). This

module is used to save the mTAC data, details in section4.4.4 (mTAC library).

application timers start() Starts the timer used to trigger a

battery level measurement.

advertising start() Now that all parameters are configured,

advertisement can be started.

telkeySetup() Initializes the mTAC library, details in

sec-tion4.4.4 (mTAC library).

After the app is initialized, there are several events that can trigger code execution. Most are connected to some external module or bluetooth communication, however the serial protocol implementation is not. on_serial_evt() is triggered whenever a serial byte has been received. The data that triggered the event is then put in the fifo created earlier. Then the event handler is scheduled for execution in normal context. In on_serial_evt_handler() the fifo is emptied and put in a buffer. If the first byte indicates that it is a command, it changes state and buffers data until it has received to expected amount of bytes for that particular command. When a command is detected, a single shot timer is started. This timer will reset the state of the function, back to scanning for known commands. This means that commands that is not finished before the time out will be considered lost. It is however necessary to implement this behaviour since the serial protocol will end up in a deadlock if waiting indefinitely. The other obvious solution to the problem is to restart whenever a known command is received despite the previous command being unfinished. However that would be hazardous since any arbitrary num-ber may be sent in some commands, resulting in a data byte being misinterpreted as a command. An important to note in this function is the fifo usage. The fifo implementation from the Nordic SDK is not re-entrant safe. Therefore data must be fetched or added in the same context level. In this case it means that we can only use the put operation in interrupt context and get in normal context.

4.4.3 BLE service

A custom bluetooth service called ”Unlock service” has been implemented. The services purpose is to handle all data related to unlocking with mTAC technology. It has the following characteristics:

Characteristic Property

Unlock Write

TABLE 2

Unlock service characteristic overview.

The service header file exports data structures and func-tions that is used in the main application:

ble unlock t A structure containing identification and

(15)

ble unlock init t This is a structure used only during ser-vice initialization. For that purpose is contains options that set the service behaviour and security.

ble unlock evt handler t This is a typedef of how to event

handler for the service is required to look. The event handler is in the main file and gets executed every time it is determined that an event belongs to this service.

ble unlock init() Function for initializing the service.

ble unlock on ble evt() Function for that determines if

the event belongs to this service.

The service lifecycle starts with the initaiation by them main app. The data structures are constructed in a way that 0 is the default value. Therefore the main application only really need to supply a pointer to the event handler. In the service initialization function itself, the UUID is set, service and characteristic added. When the characteristic is added we still have the choice to change certain permission. For instance it is possible to allow the characteristic to be read even though it is meant to be written. In the lock case however, the last code entered is sensitive information and read must not be allowed.

In the situations that someone connects to the device and performs an write to our service. A series of functions are executed; Firstly the event is sent to a dispatch function in the main application. This dispatches a series of functions that all wait for bluetooth events. Every function gets the same event and decides if it needs to take action. For instance one of the functions simply looks for connect and disconnect events. One of these functions are needs to be ble_unlock_on_ble_evt(). When a write event comes the service checks if the service handle matches is own. Then the data is meant for the service, and can be passed to the event handler. The handler, located in the main app, extracts the data, which in this case is a code and sends to an additional function. This function is not called sequentially, but rather put in the queue for the scheduler to transfer execution over to normal context. Now that the data has finally arrived to normal context, it is being sent to the mTAC library for approval. Details about the mTAC library in section4.4.4 (mTAC library).

4.4.4 mTAC library

The mTAC algorithm is currently distributed as a C li-brary with a simple API defined in the header file. The API only has two functions, telkeyCheckCode and telkeySetup, and one data type, struct codeList. telkeyCheckCode has the following format: And

Type Description

in:uint8 t Digits in code buffer, from 1 to 22

in:char* Pointer to code buffer containing ascii characters 0-9, * or # (48-57, 42 or 35).

in:uint32 t Hours since a specified date

return:uint8 t Results for provided code. Alternatives are: 0 Not valid and/or incomplete

1 Valid code found in whitelist 2 Successfully validated code 3 Valid but before time 4 Code successfully blacklisted 5 Code successfully anti-blacklisted

TABLE 3

telkeyCheckCodeinput and output parameters.

telkeySetuponly has a single argument which is a func-tion pointer to that is documented in table4 (telkeySetup):

Type Description

in:unsigned long Memory offset for accessing random numbers in:uint8 t Option (randomnumberRead/whiteListRead/

whiteListWrite/blackListRead/blackListWrite as 0/1/2/3/4)

in/out:void* Buffer for data in:uint16 t Size of data

return:uint8 t If read/write was successful (fail/success as 0/1) TABLE 4

The function telkeySetup input and output parameters.

During initialization of the main app, the function readWriteMemory is fed to the library. The function has 5 different options: Reading mTAC data, validated codes, blacklisted codes. Writing validated and blacklisted codes.

Reading mTAC data is simply a memcpy operation, this since the data is put in a specific location in flash memory as described previously in section4.3.1 (Makefile). Storing the codelists is more complex since they have only dynamically generated content. For this purpose the mod-ule Flash Data Storage (FDS) is used. FDS is a filesystem where the data is stored as a records contained in files. The records can contain any data, which gives that it is possible to simply take a struct codeList and save it with FDS. FDS also support read, update and delete of records. In the configuration file, sdk_config.h, there are two important FDS settings: FDS_VIRTUAL_PAGES and FDS_VIRTUAL_PAGE_SIZE. The total size of the FDS will be these parameters multiplied with each other times 4 bytes. One of the pages however will always be reserved for garbage collection. Garbage collection is used because rather than erasing and rewriting the record in the same spot whenever an update or write is requested on a existing record, it writes a a new record and invalidates the other. The added advantage of this is approach is data safety. A power failure in the update moment, for example, cannot result in losing the entire record. In our application this is a huge advantage and weighs the slightly added complexity to the project.

The MCU:s flash is 256kB. The region between 0x0000 and 0x1000 is reserved for the Master Boot Record (MBR). Right after this the sofdevice is placed. As the softdevice size can vary between version and settings, it is only decided at program start. The application code starts directly after the softdevice. In the other end of the flash is an optional space for bootloader that will not be used in this project, rendering that space empty for general purpose use. The FDS will automatically place the file system in the end of the flash. In our application we have reserved 6 pages that is 1024 (default physical page size). Right now that amount of space is not strictly needed so store the required information. However it is convenient to be able to store additional data in the FDS without remapping the mTAC data. The mTAC data is mapped to end just before the first page of the FDS.

(16)

than the bluetooth events. During softdevice initialization a separate dispatch function for system events have to be registered. This is where we send system events to the FDS module. If an event is for the FDS it will trigger an event handler in the main app that we registered with fds_register() before calling fds_init(). The event handler recognise events for initialization, write, update, delete file, delete record and garbage collection. In most cases nothing has to be done when an event comes in. How-ever for write and update, it is crucial that the application knows that the operation is successful. For example if we need to blacklist a code, meaning it is a valid code that must now be removed. If the application would return successful from the update operation the mTAC library would assume the code was blacklisted, if it was not it could have severe consequences. For this reason the update function has the blocking flag as illustrated in fig7.

Search for record Record found Write record Update record Wait for event Return successful no yes

Fig. 7. Function for updating codelists

This means that the application is stuck in that state in the case that something is wrong with the file system. This may seem a bit drastic, but it is a way to ensure that only a lock that is operating normally can open the door. If there is any chance that the file system has been compromised, the lock must be repaired.

4.4.5 RTC library

For mTAC to work, a way to determine real time have to be present in the system. The RTC peripheral used in the project uses I2C to communicate. The nRF52 SDK has a module for abstracting use of the internal I2C interface, that Nordic call TWI (Two Wire Interface). Any use of the TWI is further abstracted with the RTC library made for this project. Additionally it aims to abstract initialization and usage of the RTC device.

Initialization is done by a single call to the library, rx8900_init(). The function takes an instance of the TWI interface and two configuration structs. The first struct is of type nrf_drv_twi_config_t defined in the TWI module. It sets options regarding the actual I2C, such as speed and connected pins.

The second struct is the settings for the RTC itself. The RX8900 has three different registers for this: Extension, flag and control. Extension is for deciding the intervals for interrupts, flag is for detecting interrupts and control for enabling functions.

Both these structs has a default value defined in the header file to minimize the effort required for running the RTC with default settings. A normal initialization is only three rows:

1 n r f d r v t w i c o n f i g t c o n f i g =

RX8900 NRF DRV TWI DEFAULT CONFIG ; 2 RX8900 reg conf reg =

RX8900 REG CONF DEFAULT ;

3 r e t c o d e t e r r c o d e = r x 8 9 0 0 i n i t (& c o n f i g , &m twi master , &reg ) ;

If some other setting is desired all the options are defined in the header file. And the different register are accessed in the struct as ext, flag or ctrl. For example if we want to change frequency output to 1024hz and the timer to 64hz that is done in the extension register, we would only have to add a single line:

1 n r f d r v t w i c o n f i g t c o n f i g =

RX8900 NRF DRV TWI DEFAULT CONFIG ; 2 RX8900 reg conf reg =

RX8900 REG CONF DEFAULT ; 3 reg . e x t = RX8900 EXT FSEL 1024HZ |

RX8900 EXT TSEL 64HZ ;

4 r e t c o d e t e r r c o d e = r x 8 9 0 0 i n i t (& c o n f i g , &m twi master , &reg ) ;

The initialization function starts the I2C interface and then writes all three settings registers with the values previously chosen in the following order: extension, flag and control as suggested by the manufacturer12.

After initialization is successfully completed. Any of the exported functions may be called. The function declarations are: r e t c o d e t r x 8 9 0 0 w r i t e r e g s ( RX8900 reg conf ∗ ) ; r e t c o d e t rx8900 temp ( u i n t 8 t ∗ ) ; r e t c o d e t r x 8 90 0 r ea d s ec o n ds ( u i n t 8 t ∗ ) ; r e t c o d e t rx8900 read minutes ( u i n t 8 t ∗ ) ; r e t c o d e t rx8900 read hours ( u i n t 8 t ∗ ) ; r e t c o d e t rx8900 read days ( u i n t 8 t ∗ ) ; r e t c o d e t rx8900 read months ( u i n t 8 t ∗ ) ; r e t c o d e t r x 8 9 0 0 r e a d y e a r s ( u i n t 8 t ∗ ) ; r e t c o d e t r x 8 9 0 0 r e a d f l a g s ( u i n t 8 t ∗ ) ; r e t c o d e t r x 8 9 0 0 r e a d e x t e n s i o n ( u i n t 8 t ∗ ) ; r e t c o d e t r x 8 9 0 0 r e a d c o n t r o l ( u i n t 8 t ∗ ) ; r e t c o d e t r x 8 9 0 0 w r i t e s e c o n d s ( u i n t 8 t ∗ ) ;

(17)

r e t c o d e t r x 8 9 0 0 w r i t e m i n u t e s ( u i n t 8 t ∗ ) ; r e t c o d e t r x 8 9 0 0 w r i t e h o u r s ( u i n t 8 t ∗ ) ; r e t c o d e t r x 8 9 0 0 w r i t e d a y s ( u i n t 8 t ∗ ) ; r e t c o d e t rx8900 write months ( u i n t 8 t ∗ ) ; r e t c o d e t r x 8 9 0 0 w r i t e y e a r s ( u i n t 8 t ∗ ) ; r e t c o d e t rx8900 read timestamp ( t i m e t ∗ ) ; r e t c o d e t rx8900 write timestamp ( t i m e t ∗ ) ; The rx8900_write_regs() takes the same struct as the initialization function. The function might be used to recon-figure the RTC.

rx8900_temp() reads the internal temperature. It is the same thermometer used for temperature compensation of the crystal. A note is that it has an accuracy of ±5◦C, making it rather unreliable for most applications.

All functions starting with rx8900_read reads a regis-ter. Most are timekeeping, from seconds to years. Reading individual setting registers are also supported. Writing time registers are done with the corresponding functions starting with rx8900_write. All functions accept only a uint8_t pointer that is either used as source or storage depending on write or read functionality.

The functions rx8900_read_timestamp and rx8900_write_timestamp are wrapper functions for writing and reading all time registers at the same time. Additionally it uses the unix timestamp format, represented by the type time_t defined in the c standard library ctime(time.h). A unix timestamp is an integral value representing how many seconds have elapsed since the date Jan 1, 1970 at 00:00 UTC.

There are several functions in the RX8900 that has no support in the library. The reason is simply that for the current application they are not needed.

4.5 Security

4.6 Lock security

The ultimate goal when designing locks is always to prevent anyone unauthorized to open a door. To open a door you only have to break the weakest part in the locking unit. This can in some cases be the door itself, if it where to be forced open. The only thing we have to make sure is that our solution is not the weakest part. If someone forcefully opens the lock to somehow gain access to the codes, the intruder is already inside the protected area and the codes have no use. If we can ensure that it is easier to break down the door then it is to hack our lock, we have succeeded. That is why the BLE link is the focus we need, where the weakness lies. 4.6.1 BLE pairing and bonding

BLE connections have several different options and levels of security. The first step is always to pair the devices. Pairing is a temporary agreement to exchange information. This is what happens when you search for devices with your smart phone and press connect in the list of devices nearby. The actual procedure behind the pairing is:

1) Exchange of I/O capabilities 2) Set security level

3) Exchange temporary key 4) Generate short term key

5) Communicate over link encrypted with short term key

When pairing is done the bonding is simply to transfer another set of keys that is being saved in both devices so that next time the connection is instantly secure.

In the first pairing step the security level is set depending on what hardware is possible. In figure8all the options are sorted depending on the capabilities of the devices. They are

1) Just Works 2) Passkey Entry 3) Numeric comparison

Just works is for when any of the participants lack display and keyboard. In practice it is like a passkey where the key is 0.

Passkey can be used when one device have a display and the other a keyboard. It is used to prove that you are actually taking to the right device by showing numbers on the display and entering these numbers on the other device. This is a common method used in for example car stereos, where you are asked to enter the pin displayed on the stereo screen unto your smart phone.

Numeric comparison is a new method introduced in BLE version 4.2. It requires that both devices have screens and at least one have a keyboard.

Besides these another option called Out of Band (OoB) pairing may be used. Out of band is when the encryption keys are exchanged though another medium then bluetooth. Preferably one that can not be eavesdropped on. Examples include NFC, USB cable and carrier pigeon.

4.6.2 Vulnerabilities

The problem is that there are several sources claiming that the methods used, particularly methods defined before BLE 4.2, are insecure [2] [3]. Besides all the flaws, the lock in this project will, in most cases, not have a keyboard or a display available. Therefore the options available are the blue row in figure8”NuInput NoOutput” containing only the Just Works method. Because of its simple nature Just Works is very vulnerable to man in the middle (MITM) attacks. Man in the middle means a third party intercepts the communication between the two devices and claims to be the other device. Both the original devices will then think it speaks to the intended recipient but in reality the third party receives and forwards the information. Also with the option to alter the information sent.

In our case a third party could potentially attack the connection and simply decipher the code for opening the door. Then encrypt the very same code and send it to the lock. The door will open as the user had expected, but the attacker have gained access to the code. At any moment during the code’s validity period, the attacker can use it to open again.

4.6.3 Application level security

(18)

Fig. 8.The different options available when initiating a BLE con-nection. Table from BLE SIG document ”Bluetooth SIG Propri-etary Information Security”,https://www.bluetooth.com/∼/media/

files/specification/bluetooth-low-energy-security.ashx

cryptography. This means each party have a a public and private key each. Lets Call the keys Pub1, Priv1, Pub2 and Priv2. If you combine Pub1 with Priv2 a new key is created, called shared secret (SS). The same SS can then be created by combining Pub2 with Priv1. The SS is then used with another encryption algorithm to obfuscate the data.

The problem is still the MITM that can introduce a third key pair. In for example Secure Sockets Layer (SSL), used for https, this is solved by certificates. When visiting a secure website the private and public keys are exchanged as normal. The difference is that the site you are visiting have a certificate. These are normally issued by a Certificate Authority. This means that we involve a trusted third party to verify that the public key we got actually belongs to the site currently visited and not a MITM attacker.

In this project a Certificate Authority is not available, however we have another advantage: We know one of the communicating devices, the lock. When a smart phone fetches a key from the server it is for a specific lock. If this locks public key can be transferred to the phone by any other means than the BLE link we have what was previously mentioned as OoB pairing. If we give the smart phone number 1 and lock 2, the key called Pub1 and Priv1 can be created at will for every new smart phone added to the system. Pub2 and Priv2 is created when the lock is manufactured. A copy of Pub2 is then stored on the server and passed along to the smart phone when a code for that lock is requested. As illustrated in figure9, only Pub1 has to be sent over the unencrypted BLE link. This makes it impossible for third party listening to the BLE traffic

to perform a MITM attack unless the connection between the smart phone and server is compromised by the same attacker.

Fig. 9.Security

In this project the public and private keys will be gener-ated with the Elliptic curve Diffie–Hellman (ECDH) proto-col. When a common secret has been established, the data will then be encrypted with Advanced Encryption Standard (AES). AES is a block cipher that takes a key of length 128, 192 or 256 bit and a plaintext to be encrypted. The normal operation is to take data A, key K and produce encrypted data B then decrypt with K and B to get A. There are two factors that stop us from taking this approach:

Firstly block ciphers always produce the same result from the same input. Meaning if A and K is static, B will always be the same. Imagine we want to transfer a 6 digits and encrypt each digit on its own. With input 123456 the output can be anything. But if the numbers looked like this: 111222 the encoded digits would be on form: xxxyyy. Even though it is impossible to know what a single encrypted digit is, it remains trivial to guess the code since there is only 99 possibilities.

(19)

factor; thereby giving the same input different results if run several times. In this particular case Counter Mode13 will be used, see figure10. In CM the text that is encrypted is actually a nounce14 number merged with a integer that is

incremented by 1 for every chunk of data encrypted. This encrypted nonsense data, is then combined with the actual data using XOR, creating encrypted data. On the receivers end, the same nonce and counter value is encrypted creating the same nonsense which is then XOR:ed with the already encrypted data thereby restoring the data to its plaintext condition.

Fig. 10.Block cipher running in counter mode. A nonce and a counter is encrypted with a block cipher, the plaintext data is then XOR:ed with the result. The receiver performs the same encryption and the same XOR operation to retrieve the plain-text. The image is an merged version of two images made by Wikipedia user WhiteTimberwolf, https://en.wikipedia.org/wiki/ User:WhiteTimberwolf

13.https://en.wikipedia.org/wiki/Block cipher mode of operation#Counter .28CTR.29

(20)

5

D

ISCUSSION

5.1 PCB design considerations

There are several options for the PCB layout that could have minor impacts on the size of the card. For example the use of what is called via-in-pad (or plated/plugged via) could drastically reduce the complexity and length of most traces. If a standard via is placed on a solder pad, the lead will be sucked down the hole by capillary action. This may lead to a bad or missing connection making the PCB unusable. The via-in-pad method involves filling the via with a non conductive material then add another layer of copper on the plugged hole, still touching the sides of the via. This gives a perfect connection to the trace on the opposite side while leaving the top side solid. This makes it possible to place a via inside a pad.

A

B

Fig. 11.Via A represents a normal via. If a pad were to be placed on top of it, the lead would flow down into the hole leaving a bad connection. Via B has been plugged and then covered with a copper layer. From the top side is looks like a normal pad, despite working as a via.

The second and more obvious alteration is to add more layers to the PCB. However both those solutions would increase the price per unit produced without significant reduction in PCB size.

One significant advantage of having a modular solution is the PCB manufacturing. The manufacturer may need some special procedures for the PCB. For example the double sided motherboard needs two side reflow soldering. The overhead to produce such cards should be avoided to keep costs down. If only the motherboard have complex as-sembly, the overhead costs will only affect the motherboard production. The modules will probably have a simpler de-sign that is easy for the manufacturer to produce. Compare this to if every system had an unique design where this complexity was present on every new PCB.

5.2 Certifications

Before the product is sold to the customer, the company have a responsibility to ensure it is certified with all manda-tory instances. Additionally there are several certifications that may be done for either moral reasons or marketability. Because of the nature of this product it makes sense to begin with different classifications regarding locks.

Svenska St ¨oldskyddsf ¨oreningen, The Swedish Theft Pre-vention Association, has produced a rule set, SSF 20015,

15.https://www.stoldskyddsforeningen.se/foretag/ sakerhetsradgivning-for-foretag/inbrottsskydd/

which classifies building protection from 1-3, where 1 is the lowest score. SSF 200 contains a set pf sub rule sets that clas-sifies the specific products. The subset SSF 352216 classifies

mechanical and electromechanical locks and is divided in to seven classes. The term ”Approved locking unit” is the result of every part of the locking unit having at least class 3. The term is used as guidelines when insuring your home. Even though insurance companies have their own policies on the matter, it can be said that in general the following apply: In case the value of your personal property (Swedish l ¨os ¨ore) is high (above 200 000 SEK), the compensation from your insurance might be reduced without an Approved locking unit. Despite this not being relevant to most private persons, it is still a factor in marketability. The problem is that there is not certifications for Bluetooth locks. If you put any kind of radio transceiver in the lock, there are no classifications available. The customer will simply have to make their own judgement, assessing that the advantage of our lock is worth not being approved.

Within the EU all consumer product is required to have a CE(Conformit´e Europ´eenne) certification. The CE certifi-cation is divided into several categories where one product may fall under more than one. The manufacturer, in this case Telkey, is responsible to prove that their product is within the limits and/or exceeds the requirements for all categories that apply. This may be done by the manufacturer itself as long as documentation that proves the product passed all test can be provided upon request. However there are companies that provide certification services, one of which is SP Sveriges Tekniska Forskningsinstitut owned by the Swedish government. The test documents will then be provided by a accredited lab, thereby alleviating the manufacturer of some of the responsibility.

The CE certifications needed for our product will be determined by an accredited test lab, however two cate-gories are certain to be necessary. First it is EU directive 2014/30/EU about products generating or being affected by electromagnetic radiation. The second is RoHS (Restriction of the use of certain Hazardous Substances in electrical and electronic equipment), a directive that makes the manufac-turer or importer or distributor responsible for the levels of hazardous materials in the end product.

5.3 CE and modules

The hassle with CE certification in our case comes from the concept of an end product. The end product that the customer buys as a separate product must be certified as a single unit. If we for example were to sell the lock with our motherboard inside, the entire lock including mother-board have to pass all the tests as one unit. Regardless of the fact that both products could have been already CE certified individually. This also means that if any of the future modules where to be sold separately, Telkey may not assemble the module with the lock. That would entitle it a new product and need new certifications. This can somewhat be dodged by training external companies to handle the assembly and then recommend customers to use

(21)

these partners. But nonetheless it is a considerable problem for the modular solution.

5.4 System functionality

Several possible module functionalities have been consid-ered before the current motherboard was decided on. These include keyboards, LED:s, speakers, displays and other radio protocols. As was described in section2.2 (Modular

solution), the motherboard provides processing power,

de-bug capabilities, external communication and power. These are all necessary for the base requirement of the system, to open the lock. Bluetooth was used added for its leading position in the market. The only real competitor for the smartphone market is WiFi. But with a higher production cost and less energy efficiency it is simply not a viable option. And judging by other products being released, it is not a difficult choice. When the communication only needs to be between two devices, there is no need to use WiFi.

Human interfacing with displays and sounds is not a good choice for a general purpose system. Any such details will be highly dependent on the current product, it will therefore be beneficial to place these options on modules.

The greatest consideration during the project was whether to include a Long Range radio protocol such as, LoRaWAN17. The technology could provide means for the locks to get and provide information from/to web servers without using conventional wireless technology such as 3G. By using LoRa one sacrifices data rate for a great gain in power and portability. LoRa is made with battery powered sensor systems in mind. However the need of Low Range radio is not great enough to justify installing it in every system. The functionality is be to specialised to justify the increased cost on systems where it would not be used.

5.5 Conclusion

For the modular solution to be a viable development policy, it have to save enough time to make up for the added problems and costs regarding certifications. This is not easily quantifiable parameters. The overhead for creating a modular system must be weighed against the benefits for all relevant projects, both current and foreseeable. This is simply a decision that have to be internally discussed within the company. However the flexibility gain while developing new similar systems is significant and in most cases outweighs the overhead. I find a modular system to be preferred instead of redoing the entire design for every project.

(22)

A

PPENDIX

A

S

CHEMATIC

,

PROTOTYPE

1

1 2 3 4 5 6 1 2 3 4 5 6 A B C D A B C D Date: 2017-04-11

KiCad E.D.A. kicad 4.0.5

Rev: 0.1

Size: A4

Id: 1/1

Title: BLE lock File: modelx.sch Sheet: / Telkey Prototype 1

DCC 1 DEC4 2 GND 3 VCC_NRF 4 GND 5 P0.04_AIN2 6 P0.05_AIN3 7 P0.06 8 P0.07 9 P0.08 10 P0.21_RESET 20 P0.28_AIN4 30 P0.19 40 NFC1_P0.09 11 GND 21 P0.29_AIN5 31 P0.20_TRACECLK 41 NFC2_P0.10 12 OUT_MOD 22 P0.30_AIN6 32 GND 42 GND 13 OUT_ANT 23 P0.31_AIN7 33 GND 43 SWDIO 14 P0.22 24 P0.02_AIN0 34 GND 44 SWDCLK 15 P0.23 25 P0.03_AIN1 35 GND 45 P0.13 16 P0.24 26 P0.11 36 NC 46 P0.14_TRACEDATA[3] 17 P0.25 27 P0.12 37 GND 47 P0.17 18 P0.26 28 P0.15_TRACEDATA[2] 38 GND 48 P0.18_TRACEDATA[0] 19 P0.27 29 P0.16_TRACEDATA[1] 39 NC 49 U2 EYSHCNZXZ FOE 1 VDD 2 VBAT 3 FOUT 4 SCL 5 T1 6 SDA 7 T2 8 GND 9 /INT 10 U3 RX8900CE VIN 1 VOUT 2 VSS 3 U1 XC6218P302HR-G VCC_NRF GND GND C2 0.1uF C1 0.1uF VCC_NRF For internal DCDC

For using built in antenna

GND GND GND GND SWDIO SWDCLK VTref 1 SWDIO 2 nRESET 3 SWDCLK 4 GND 5 SWO 6 P1 TC2030-CTX-NL GND GND GND GND SWDIO SWDCLK GND VCC_NRF SWO SWO Reset Reset VCC_NRF SCL SDA GND C5 0.1uF

alarm Open drain. 0 indicates alarm

(23)

A

PPENDIX

B

E

RROR HANDLING

1 void a p p e r r o r f a u l t h a n d l e r ( u i n t 3 2 t id , u i n t 3 2 t pc , u i n t 3 2 t i n f o ) 2 {

3 // On a s s e r t , t h e system can only r e c o v e r with a r e s e t . 4 # i f n d e f DEBUG 5 NVIC SystemReset ( ) ; 6 # e l s e 7 8 unsigned i n t tmp = i d ; 9 NRF LOG DEBUG( ” F a u l t i d e n t i f i e r : 0x%X\ r \n ” , tmp ) ; 10 NRF LOG DEBUG( ” Program c o u n t e r : 0x%X\ r \n ” , tmp = pc ) ; 11 NRF LOG DEBUG( ” F a u l t i n f o r m a t i o n : 0x%X\ r \n ” , tmp = i n f o ) ; 12

13 sw i t c h ( id )

14 {

15 c a s e NRF FAULT ID SDK ASSERT :

16 NRF LOG DEBUG( ” Line Number : %u\ r \n ” , tmp = ( ( a s s e r t i n f o t ∗ ) ( i n f o ) )−> line num ) ;

17 NRF LOG DEBUG( ” F i l e Name : %s \ r \n ” , ( ( a s s e r t i n f o t ∗ ) ( i n f o ) )−> p file name ) ;

18 break ;

19

20 c a s e NRF FAULT ID SDK ERROR :

21 NRF LOG DEBUG( ” Line Number : %u\ r \n ” , tmp = ( ( e r r o r i n f o t ∗ ) ( i n f o ) )−> line num ) ;

22 NRF LOG DEBUG( ” F i l e Name : %s \ r \n ” , ( ( e r r o r i n f o t ∗ ) ( i n f o ) )−> p file name ) ;

23 NRF LOG DEBUG( ” E r r o r Code : 0x%X\ r \n ” , tmp = ( ( e r r o r i n f o t ∗ ) ( i n f o ) )−> e r r c o d e ) ;

24 break ;

25 }

26

27 app error save and stop ( id , pc , i n f o ) ; 28

(24)

A

PPENDIX

C

PCB

(25)

References

Related documents

46 Konkreta exempel skulle kunna vara främjandeinsatser för affärsänglar/affärsängelnätverk, skapa arenor där aktörer från utbuds- och efterfrågesidan kan mötas eller

The increasing availability of data and attention to services has increased the understanding of the contribution of services to innovation and productivity in

Parallellmarknader innebär dock inte en drivkraft för en grön omställning Ökad andel direktförsäljning räddar många lokala producenter och kan tyckas utgöra en drivkraft

I dag uppgår denna del av befolkningen till knappt 4 200 personer och år 2030 beräknas det finnas drygt 4 800 personer i Gällivare kommun som är 65 år eller äldre i

DIN representerar Tyskland i ISO och CEN, och har en permanent plats i ISO:s råd. Det ger dem en bra position för att påverka strategiska frågor inom den internationella

Det finns många initiativ och aktiviteter för att främja och stärka internationellt samarbete bland forskare och studenter, de flesta på initiativ av och med budget från departementet

Industrial Emissions Directive, supplemented by horizontal legislation (e.g., Framework Directives on Waste and Water, Emissions Trading System, etc) and guidance on operating

A thermodynamic slag model was developed at the Division of Metallurgy, which has the feature to not only estimate the thermodynamic activities of slag systems, but also