trustzone-backed bitcoin wallet - ulisboa · of bitcoin, since it is a decentralized digital...

89
TrustZone-backed Bitcoin Wallet Miraje Gentilal Thesis to obtain the Master of Science Degree in Electrical and Computer Engineering Supervisor: Dr. Leonel Augusto Pires Seabra de Sousa Examination Committee Chairperson: Dr. Gonçalo Nuno Gomes Tavares Supervisor: Dr. Leonel Augusto Pires Seabra de Sousa Members of the Committee: Dr. Ricardo Jorge Fernandes Chaves November, 2016

Upload: others

Post on 01-Jun-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

TrustZone-backed Bitcoin Wallet

Miraje Gentilal

Thesis to obtain the Master of Science Degree in

Electrical and Computer Engineering

Supervisor: Dr. Leonel Augusto Pires Seabra de Sousa

Examination CommitteeChairperson: Dr. Gonçalo Nuno Gomes Tavares

Supervisor: Dr. Leonel Augusto Pires Seabra de SousaMembers of the Committee: Dr. Ricardo Jorge Fernandes Chaves

November, 2016

Page 2: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that
Page 3: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

AcknowledgmentsI would like to thank to all those who, in some way, contributed for this dissertation by supporting

and encouraging me.To my supervisor, Doutor Leonel Sousa, for introducing me to the topic, providing me with

guidance, and for permanent availability shown. His knowledge and support were fundamental duringthe process of developing this dissertation.

To Paulo Martins for his helpful advices, suggestions, critical comments, and for his unconditionalsupport through the writing process of this dissertation.

To Instituto Superior Técnico (IST) and Instituto de Engenharia de Sistemas e Computadores -Investigação e Desenvolvimento (INESC-ID) for providing me with all the needed resources to developthis dissertation.

To my family and friends who have supported me at all times and gave me strong motivation.Thank you for always reminding me what my priorities are and for encouraging me to follow my dreams.

Lastly, to all those who I did not have the opportunity to mention as I should, my sincere thank you.

i

Page 4: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

ii

Page 5: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

ResumoNos últimos anos, a popularidade das moedas virtuais tem aumentado em grande parte devido à

crescente aceitação de Bitcoin, cujo núcleo é baseado na criptografia de chave pública. Enquantoque a chave pública é utilizada como endereço destino de um pagamento, a chave privada é usadapara aceder aos fundos armazenados no endereço correspondente, através da assinatura digital detransações.

A maioria das carteiras de Bitcoin processam a informação sensível num ambiente susceptível aataques. Além disso, a segurança que é atribuída ao armazenamento dessa informação é suportadana sua encriptação com uma chave baseada na palavra-passe do utilizador, tornando-se suscetível aataques de dicionário. Como a chave privada define a posse dos bitcoins, deve ser muito bem protegidae guardada, criando assim a necessidade de se utilizar medidas de segurança mais robustas do queas que são utilizadas atualmente.

A ARM tornou disponível uma extensão da arquitetura dos processadores denominada de Trust-Zone, que permite separar ambientes seguros e não seguros, garantindo simultaneamente a integri-dade do código do Sistema Operativo.

Nesta dissertação, é proposta a exploração da TrustZone para implementar uma carteira de Bitcoinsflexível, confiável e resistente a ataques de dicionário e de canal lateral. A utilização desta extensãotem a desvantagem de a execução das operações de leitura e escrita serem mais lentas devido àencriptação do armazenamento. Contudo, como resultado das otimizações específicas associadas àplataforma através do uso duma interface de programação da TrustZone é demonstrado que as oper-ações criptográficas podem, de facto, ser mais eficientes.

Palavras-Chave: Ambiente de Execução Confiável; Bitcoin; Carteira de Bitcoins; Carteirade Hardware; Mundo Seguro; TrustZone.

iii

Page 6: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

iv

Page 7: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

AbstractThe popularity of virtual currencies has been increasing in the recent years, largely due the growing

acceptance of Bitcoin, whose core is based on public key cryptography. While the public key is usedas an address for a payment, the private key is used to access the funds stored in the correspondentaddress, through the digital signature of transactions.

Sensitive information is processed in an environment susceptible to attacks in almost every Bitcoinwallet. Moreover, the security that is provided to store such information, is supported on the encryptionwith a key based in a user’s password, making it susceptible to dictionary attacks. As the private keydefines the ownership of bitcoins, it must be very well protected and secured. Thus, the need of usingstronger security measures than the ones that are currently used arises.

ARM has made available an extension of processors architectures, designated TrustZone, whichallows for the separation of trusted and non-trusted environments, while ensuring the integrity of theOperating System code.

In this dissertation, it is proposed the exploitation of TrustZone, in order to implement a flexibleand reliable Bitcoin wallet that is more resilient to dictionary and side-channel attacks. Making usethis extension comes with the downside that writing and reading operations become slower, due to theencrypted storage, but it is shown that cryptographic operations can in fact be executed more efficientlyas a result of platform-specific optimizations, which are available through the use of a TrustZone API.

Keywords: Bitcoin; Bitcoin Wallet; Hardware Wallet; Secure World; Trusted Execution Environ-ment; TrustZone.

v

Page 8: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

vi

Page 9: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

Contents

Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iResumo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iiiAbstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vList of Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ixList of Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiAcronyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

1 Introduction 11.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.2 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.3 Main Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.4 Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Background 72.1 TrustZone Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2.1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.1.2 Hardware Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.1.3 Software Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.1.4 Security Features and Economic Impact . . . . . . . . . . . . . . . . . . . . . . . . 11

2.2 Bitcoin Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.2.1 Bitcoin Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.2.2 Bitcoin Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.2.3 Bitcoin Transaction Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162.2.4 Bitcoin Wallets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182.2.5 Security Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2.3 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

3 Proposed TrustZone-based Bitcoin Wallet 233.1 Available Base Wallets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243.2 Base Wallet Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.3 Proposed Improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

4 Implementation Details and System Assessment 434.1 TrustZone-enabled Platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444.2 Software Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464.3 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

vii

Page 10: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

4.3.1 Platform Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484.3.2 Implementation Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

4.4 Experimental Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

5 Conclusion 615.1 Summary and Overall Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625.2 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Bibliography 65

viii

Page 11: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

List of Tables

2.1 Main types of Bitcoin Wallets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

3.1 Main Hardware Wallets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253.2 BitSafe’s development prototype main characteristics [87]. . . . . . . . . . . . . . . . . . . 273.3 Brief description of the main Wallet Functions [11]. . . . . . . . . . . . . . . . . . . . . . . 313.4 Brief description of the main Transaction Functions [11]. . . . . . . . . . . . . . . . . . . . 313.5 Brief description of the main Pseudo-Random Number Generation Functions [11]. . . . . 323.6 Brief description of the platform dependent functions [11]. . . . . . . . . . . . . . . . . . . 323.7 Available packets for the communication between BitSafe and the host [11]. . . . . . . . . 33

4.1 Processors with TrustZone support. [101, 102] . . . . . . . . . . . . . . . . . . . . . . . . 444.2 Main characteristics of TrustZone-enabled development boards. . . . . . . . . . . . . . . 454.3 Execution time of storage related functions. The values are presented in clock cycles. In

parenthesis the execution time increase in percentage of the TBW relative to the OBW ispresented. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

4.4 Execution time of the used Cryptographic Operations. The values are presented in clockcycles. In parenthesis the execution time increase in percentage of the TBW relative tothe OBW is presented. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

4.5 Execution time of the available packets. The values are presented in clock cycles. Inparenthesis the execution time increase in percentage of the TBW relative to the OBW ispresented. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

4.6 Qualitative comparison between the OBW and the TBW. . . . . . . . . . . . . . . . . . . . 59

ix

Page 12: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

x

Page 13: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

List of Figures

1.1 Total USD value of trading volume on major bitcoin exchanges per day since the imple-mentation of the Bitcoin protocol (logarithmic scale) [12]. . . . . . . . . . . . . . . . . . . . 3

1.2 Number of confirmed transactions per day since the implementation of the Bitcoin protocol(logarithmic scale) [12]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2.1 Possible software design for the Trusted Execution Environment [28]. . . . . . . . . . . . . 92.2 Simplified structure and flow of the Bitcoin architecture. . . . . . . . . . . . . . . . . . . . 132.3 Example of a fork in the blockchain. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.4 Simplified Bitcoin transaction example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172.5 Example of real Bitcoin transactions with some information about the scripts used [54, 55]. 18

3.1 On the left it is displayed how the Storage is partitioned, and on the right it is shown theinformation stored in each wallet. The represented memory is byte addressable. . . . . . 28

3.2 The three main modules of the BitSafe wallet. . . . . . . . . . . . . . . . . . . . . . . . . . 303.3 BitSafe’s main modules. a) Initial configuration. b) Final configuration. The dotted boxes

are fully implemented in the Normal World, the dashed boxes are partially implementedin the Secure World and the full boxes are completely implemented in the Secure World.Some of the Cryptographic Operations are only used to implement the functions of theboxes they are contained. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

4.1 OP-TEE software architecture [112]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474.2 OP-TEE secure storage architecture [14]. . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

xi

Page 14: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

xii

Page 15: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

Acronyms

AES Advanced Encryption StandardAMBA Advanced Microcontroller Bus ArchitectureAPI Application Programming InterfaceARM Advanced RISC MachineAXI Advanced eXtensible InterfaceBIP Bitcoin Improvement ProposalCA Client ApplicationCPU Central Processing UnitDRBG Deterministic Random Bit GeneratorDRM Digital Rights ManagementECC Elliptic Curve CryptographyECDSA Elliptic Curve Digital Signature AlgorithmGCC GNU Compiler CollectionHD Hierarchical DeterministicHMAC Hash-based Message Authentication CodeIP Intellectual PropertyOBW Original Base WalletOEM Original Equipment ManufacturerOP-TEE Open Source Trusted Execution EnviornmentOS Operating SystemP2PKH Pay To Public Key HashPBKDF2 Password-Based Key Derivation Function 2REE Rich Execution EnvironmentRIPEMD RACE Integrity Primitives Evaluation Message DigestSCP Secure CopySDK Software Development KitSHA Secure Hash AlgorithmSMC Secure Monitor CallSoC System on ChipSSH Secure ShellTA Trusted ApplicationTBW TrustZone-backed Bitcoin WalletTEE Trusted Execution Environment

xiii

Page 16: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

xiv

Page 17: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

CHAPTER 1

INTRODUCTION

Contents

1.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.2 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.3 Main Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.4 Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1

Page 18: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

In the last few years, the Internet availability has been increasing at a steady pace, and at the endof June 2016 it was used by almost half (49.2%) of the world’s population [1]. This widespread usemade the Internet a very powerful platform for exchanging information, perform business operations,and create new technological concepts.

One concept that has been increasing its popularity in the recent years is Virtual Currency [2]. Thereare several different types of virtual currency but one in particular, Bitcoin, had a great part in the inte-gration of this concept among different types of markets, specially in the financial and business sector.

The term Bitcoin first emerged in A Peer-to-Peer Electronic Cash System [3], a publication released inNovember 2008 under the pseudonymous Satoshi Nakamoto who described it as an “electronic paymentsystem based on cryptographic proof instead of trust, allowing any two willing parties to transact directlywith each other without the need for a trusted third party ” [3]. The Bitcoin protocol is considered to be thefirst one of its kind, it uses a peer-to-peer network to generate and exchange digital currency as well asto verify all the performed transactions [4, 5]. This characteristic could be considered the most importantof Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank,authority or government that is in charge of the network.

Since the users have full control of their money, there are several advantages in using this innova-tive currency, such as low fees and irreversible transactions that do not reveal any personal informa-tion. Moreover, transactions can be verified by everyone through a public ledger leading to a strongerprotection against frauds [6]. Every transaction makes use of public key cryptography, viz., to maketransactions a user needs to be able to generate cryptographic key-pairs and store private information.The private keys are used to sign transactions, and consequentially spend the funds stored in the cor-responding public keys, also known as Bitcoin addresses. As the private key is essentially what definesthe ownership of bitcoins, it must very well protected and secured.

TrustZone® is a technology that was developed by ARM® as an extension of processors and systemarchitectures to increase their security [7]. It enables a logical separation between a secure and anon-secure environment, and when combined with a well designed system and secure software it canensure that sensitive data remains safe, no matter what the non-secure environment does [7]. Thesetechnological characteristics make it very attractive for payment services, authentication processes, andto handle confidential information in a secure manner. A recent example is the Knox mobile securityplatform announced by Samsung® in 2013, which uses the TrustZone technology to perform securityservices, integrity measurements, and securely store information [8].

1.1 Motivation

As bitcoins are considered the “next logical step in financial operations” [9], its usage will become in-creasingly commonplace. In fact, the amount of bitcoins exchanged per day (Figure 1.1) has growndrastically as well as the number of transactions performed each day (Figure 1.2). A recent proof ofthis fact is that, in the last years, many Venezuelan citizens started to abandon the bolivar and beganto adopt this virtual currency as an escape hatch for the inflation and strict capital controls, which leadin the first week of August 2016 to a new record of Bitcoin trading volume that reached 141,744,733bolivars (about $141,000 USD) [10].

With the increasing trust that is deposited on Bitcoin, the need of using stronger security measuresthan the ones that are currently used arises. For example, using a user’s password, which can be easilyguessed, to encrypt private information has proven to be a weak-point for Bitcoin wallets [11]. Also,the process of signing transactions should be executed in a secure environment, where the use of theprivate key is quite safer. While sensitive data can be stored or transmitted in a protected form, itsprocessing is usually done in the clear, which means that it can easily be exposed to an attacker and

2

Page 19: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

may end up having catastrophic consequences.Due to these reasons, the main motivation behind this dissertation is to exploit the TrustZone technol-

ogy to develop a flexible Bitcoin wallet, increase the security behind the generation of keys, their storageand the process of signing each transaction.

$1.00

$10.00

$100.00

$1,000.00

$10,000.00

$100,000.00

$1,000,000.00

$10,000,000.00

$100,000,000.00

$1,000,000,000.00

Jan-09 Jan-10 Jan-11 Jan-12 Jan-13 Jan-14 Jan-15 Jan-16

Am

ou

t ex

chan

ged

per

day

Time (day)

Figure 1.1: Total USD value of trading volume on major bitcoin exchanges per day since the implemen-tation of the Bitcoin protocol (logarithmic scale) [12].

1

10

100

1000

10000

100000

1000000

Jan-09 Jan-10 Jan-11 Jan-12 Jan-13 Jan-14 Jan-15 Jan-16

Nu

mb

er o

f tr

ansa

ctio

ns

per

day

Time (Day)

Figure 1.2: Number of confirmed transactions per day since the implementation of the Bitcoin protocol(logarithmic scale) [12].

1.2 Objectives

The main purpose of this dissertation is to examine the TrustZone technology and the Bitcoin proto-col, and through a careful analysis of how to improve Bitcoin wallets on TrustZone-enabled devices,implement a highly secure TrustZone-backed Bitcoin wallet.

To this end, first, the characteristics of TrustZone are explored to find out which are the securityfeatures associated with this technology. Then, the Bitcoin protocol and the different types of Bitcoinwallets that are available will be analyzed, in order to find the one that is more prone to benefit from thehigh security level of TrustZone. With those notions, a Bitcoin wallet will be deployed into a TrustZone-capable platform to provide enhanced security and functionality. It will also be experimentally assessedthe execution time of the read and write operations on the wallet storage, of the cryptographic operations,and of the wallet functions that are most commonly used.

3

Page 20: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

Furthermore, it is intended to develop a Bitcoin wallet that is efficient and platform-independent soit could support any embedded TrustZone-enabled device without compromising the execution perfor-mance. Moreover, it is also intended that the platform where the wallet is deployed to be capable ofsupporting other applications without compromising the security level provided to the wallet.

Lastly, it is aimed to make the wallet available as open-source so that everyone can access it. In thisway, it is created a more transparent solution that can be verified, customized, and improved by anyonewith associated low costs.

1.3 Main Contributions

With the TrustZone-based Bitcoin wallet developed and presented in this dissertation it is shown that itis possible to have a Hardware Bitcoin wallet with an additional security layer provided by the TrustZone,and still have the flexibility provided by software solutions which until now was not possible.

The platform used to implement the developed Bitcoin wallet was the ARM Juno-r2 board [13]. How-ever in its initial state it was not possible to develop applications that could make use of the TrustZone.For that, some additional software was needed like the Open Source Trusted Execution Enviornment(OP-TEE) [14]. During the setup of the development environment, several contributions were made tothe OP-TEE project, namely:

• The OP-TEE supported several platforms including the ARM Juno board, however, this supportwas only available for earlier versions of the platform, more specifically, for the Juno-r0 and Juno-r1 editions. The most recently released one, Juno-r2, was not supported yet and modificationshad to be applied to the available software to add that possibility. The performed changes werereported and integrated into the OP-TEE project [15] so it could support the ARM Juno-r2 boardnatively;

• While developing an application that would run on the TrustZone, some features were detected tobe missing from persistent objects which would make them not store some important information[16], consequently, they did not work as it was expected. When this matter was reported to theOP-TEE developers it was suggested a test case to detect this problem. Later, this test case wasintegrated into the OP-TEE test suite case [17];

• As part of the OP-TEE development process, the complier that was used was upgraded to theGNU Compiler Collection (GCC) 5, and that change required a copy of quite a few more filesthan before to the root file system. As a consequence, there was an increase of the RAM diskimage file (ramdisk.img) size that exceeded its predefined Juno memory flash reserved location,thus it became impossible to use the OP-TEE software in this state [18]. To get around this sizelimitation, the addresses that defined where the images were loaded into the Juno’s flash memorywere modified and rearranged. Then, the changed addresses were shared with the OP-TEEdevelopers [19] and now they are part of the instructions to get and build the OP-TEE software forthe ARM Juno board, which are available on the OP-TEE’s GitHub page [20] and on the OP-TEEofficial website [21].

• The development cycle of an application in an ARM Juno board with OP-TEE consists in writingits source code, compiling it and including it in the root file system that is integrated in the RAMdisk image. This means that every time that a change is done within the application, it is neededto compile the whole RAM disk image again with the new version of the application, and thenflash it to the board. As this approach is very time consuming for the normal development processand it does not allow to develop remotely, it was developed a solution that consisted in adding the

4

Page 21: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

support of Secure Shell (SSH) and Secure Copy (SCP) to the current setup. This information wasalso made available so that every developer could benefit from it [22, 23].

More details about OP-TEE and the ARM Juno-r2 Board as well as the specific modifications thatwere made are provided in Chapter 4.

In the developed work, a detailed analysis was made of how to make an existing Bitcoin wallet saferby examining which components should be transfered to the TrustZone’s secure environment. Althoughthis analysis is applied to a Bitcoin wallet, it could easily be extended to other applications making thisdissertation an open work. Up until now, there was not any work in the existing literature that presentedexperimental results about the execution of the transferred functions to the TrustZone. In this dissertationis evaluated the impact on the performance of the modules that were transferred to the TrustZone, andprovided a detailed analysis of the results

The developed Bitcoin wallet uses the TrustZone to perform some cryptographic operations like Se-cure Hash Algorithm (SHA), Hash-based Message Authentication Code (HMAC) or Advanced Encryp-tion Standard (AES), and as these functions are commonly used among security applications the walletcan easily be modified into applications such as home-banking or for authentication purposes. More-over, the presented wallet is platform-independent and is available as open-source, so that it can alsobe scrutinized by the scientific community in order to further improve its safety, and at the same timeit can be adapted and integrated in other products by any manufacturer or developer as a way to addmore functionality.

As one of the last contributions, the Bitcoin wallet proposed in this dissertation was described in apublication that was submitted, and is waiting for acceptance, to the 19th Annual International Confer-ence on Information Security and Cryptology that takes place in Seoul, Korea:

• Miraje Gentilal, Paulo Martins, and Leonel Sousa, “TrustZone-based Bitcoin Wallet,” in: The 19thAnnual International Conference on Information Security and Cryptology, 2016.

1.4 Outline

The remainder of this dissertation is organized as follows. Chapter 2 starts with a detailed overviewabout the TrustZone, where the impacts that the hardware architecture has on the infrastructure wherethis technology is applied are explained. Possible software architectures that can exploit this securityextension are also presented. Furthermore, the security features that are available with the use ofTrustZone are discussed, as well as its economical impact. Afterwards, the Bitcoin protocol is described,with a special emphasis on address generation, the transaction process, and on the types of walletsthat are available. Then, an analysis about the security features associated with the use of this digitalcurrency is made. The chapter ends with a review of related work.

A TrustZone-based Bitcoin wallet is proposed in Chapter 3. First, the base wallet that will be en-hanced with the security features of a TrustZone-enabled platform will be analyzed in detail. After havingdetermined the main modules of this wallet, they are evaluated in terms of their security, and proposalsare made on how to improve their confidentiality and integrity by exploiting the TrustZone technology.

In Chapter 4, proposed enhancements are implemented and evaluated. The procedure followedto configure the TrustZone-enabled platform with all the required software is described. It should benoted that this process was not trivial, since several elements were lacking for the correct exploitation ofthe TrustZone. Then, the modifications to the chosen wallet to integrate the new selected features arepresented. Finally, the results obtained for the executions times before and after applying the proposedmodifications are presented and analyzed. The security features of the proposed wallet will also be

5

Page 22: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

qualitatively compared with the original one. Lastly, Chapter 5 contains the overall conclusions andadditional features that could be implemented in a future work.

6

Page 23: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

CHAPTER 2

BACKGROUND

Contents

2.1 TrustZone Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2.1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2.1.2 Hardware Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2.1.3 Software Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.1.4 Security Features and Economic Impact . . . . . . . . . . . . . . . . . . . . . . 11

2.2 Bitcoin Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2.2.1 Bitcoin Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2.2.2 Bitcoin Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2.2.3 Bitcoin Transaction Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

2.2.4 Bitcoin Wallets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

2.2.5 Security Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2.3 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

7

Page 24: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

An increasing concern over the security of the implementations of cryptographic protocols has ledARM to release an hardware-backed technology to enhance the integrity and confidentiality of theseimplementations. In this section, it is described this technology in depth, as well as the Bitcoin protocol,for which wallets supported on TrustZone will be proposed in Chapter 3.

First, the TrustZone technology is overviewed, as it is important to understand how it is integratedin the ARM architecture. The interconnections enabled by the TrustZone between the software and thehardware will be presented from an architectural point of view. It is also highlighted the security featuresderived from the use of the TrustZone and its economical impact.

Then, the Bitcoin protocol is described in detail, as a way to identify the critical points of its architec-ture in terms of security and privacy. To that end, the general concepts on which Bitcoin is based arepresented. Some of the most sensitive operations like Bitcoin address generation and the transactionprocess are carefully discussed. Bitcoin wallets are also presented as they are responsible for handlingthe aforementioned operations. The security features of Bitcoin are also referred. Afterwards, relatedwork in TrustZone and virtual currencies is presented.

2.1 TrustZone Technology

TrustZone is a technology developed by ARM that aims to establish trust into any platform that uses itsarchitecture, which is widely deployed specially among smart devices platforms. This technology takesadvantage of the internal hardware that is located within the System on Chip (SoC) along with softwarecomponents to create a secure and trusted environment where confidentiality and integrity of almost anyasset can be guaranteed [7, 24]. In this way, a flexible framework is provided that semiconductor andOriginal Equipment Manufacturer (OEM) developers can use it in order to implement their own securityfeatures with minimal impact on power consumption, performance and area, which otherwise would bemuch more expensive to obtain [24].

2.1.1 Overview

This technology relies on two distinct concepts of virtual worlds that exist within the same SoC. On onehand, there is the Secure World, that is responsible for the security subsystem and, consequently, forthe execution of trusted software, accessing sensitive hardware and processing critical data. Thus, it ispossible to have applications that can access secure memory space and peripherals with the guaranteethat the provided data was not tampered with and is trustworthy [7]. These applications are only executedin the Secure World and therefore are also known as Trusted Applications (TAs).

On the other hand, everything that is not handled by the Secure World is the responsibility of theNormal World, which is the common execution environment where applications, apart from TAs, run [7].There is the possibility for certain applications that run in this world to communicate with TAs, which areusually called Client Applications (CAs).

Usually, these two worlds exist in two separate virtual cores inside the same physical processor,and there is a core mode that manages the switching between them, the monitor mode. The entry tothis mode is strictly controlled when made by the Normal World, which is only possible through explicitSecure Monitor Calls (SMCs), interrupt exceptions, or external abort exceptions. For the Secure Worldthis entry is a little more flexible, and can be achieved by directly writing to Current Program StatusRegister [25], in addition to the exception mechanisms already available to the Normal world [7].

Moreover, each of these worlds can have an Operating System (OS) of its own. In the Secure World,the OS is termed Trusted OS, and in the Normal World it is denominated Rich OS. With a cryptographi-cally secure boot of the Trusted OS, the Secure World becomes a Trusted Execution Environment (TEE)

8

Page 25: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

which is able to provide “end-to-end security by enforcing protected execution of authenticated code,confidentiality, authenticity, privacy, system integrity and data access rights” [26].

Due the different possible configurations of the platforms where the TEE can be implemented, it be-comes essential to standardize it, not only to allow interoperability but also to lower the costs associatedwith the development and integration of the TAs. GlobalPlatform [27] is an industry association that hasbeen responsible for driving TEE standardization by presenting some guidelines like the TEE SystemsArchitecture [28] which explains the hardware and software architectures behind the TEE, and by re-leasing Application Programming Interfaces (APIs) such as: the TEE Client API Specification [29] thatdefines the communication between CAs and TAs; TEE Internal Core API Specification [30] that is usedby the TAs to perform general security functions; and Trusted User Interface API Specification [31] thatallows the TAs to safely display text and graphics by securely communicating with the peripherals.

In this way, the standard mandated scenario would be to have a TEE implemented in accordancewith TEE Systems Architecture, and which had an Trusted OS that offered to the TAs, at least, the TEEInternal Core API, and if possible the Trusted User Interface API. In turn, the TAs should use, wheneverit is possible, the previous mentioned APIs to perform their operations, and should communicate withthe CAs through well defined entry-point calls using the TEE Client API. Following this methodology, itis possible to create secure applications for content protection, financial services, cryptographic opera-tions, and user authentication [32] that are platform-independent. In Figure 2.1, it is depicted a simplifieddesign of the previously mentioned scenario.

Common Execution Environment TEE

Secure Hardware Resources(crypto, timers, watchdog, screens, keyboard, ...)

Secure Monitor

Trusted OS

Trusted Application

1

Trusted Application

2

Security Service

ARM TrustZone-enabled Chipset

TEE Internal Core API

StorageRich OS

TEE Client API

Generic Application

Security Client

CA with TA support

Trusted User Interface APIPri

vile

ged

sp

ace

Use

r sp

ace

Pri

vile

ged

sp

ace

Use

r sp

ace

Figure 2.1: Possible software design for the Trusted Execution Environment [28].

2.1.2 Hardware Architecture

The TrustZone architectural way of achieving a TEE is to have a single physical processor core runningthe two virtual worlds in a time-slice fashion [7], each one with a different vision of the SoC’s hardwareand software resources to ensure that none of the Secure World protected resources are accessibleoutside the trusted environment.

To manage the conditional access to the resources, additional bits were added to main system bus.One could also say that Non-Secure bits were added to the ARM’s Advanced Microcontroller Bus Archi-tecture (AMBA) with Advanced eXtensible Interface (AXI) [7, 33]. The existent hardware logic in the bus

9

Page 26: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

fabric guaranties that there is not any violation on the access of the hardware and software designatedas secure [7]. Therefore, the available memory can be split in secure and non-secure regions, and whilethe former region is only visible to the Secure World, the latter region is accessible to both worlds cre-ating the possibility of using shared memory regions between them for communication purposes. Theaccess to secure peripherals and cache memories is conditioned in the same manner.

When there is the need to switch between worlds one resorts to the Secure Monitor, which is wherethe monitor mode is executed. When the Secure Monitor receives the instruction to switch world, it storesthe currently running context and loads the previously stored one for the world for which is changingto. It is important to notice that on monitor mode the processor is always executing the Secure Worldregardless of the world that requested the switch, in order that the context information is stored in securememory regions preventing it from being compromised .

An important part of the TrustZone hardware architecture is the debug solution provided. There aretwo settings that define the debug range, one that indicate evasiveness level, and another which indi-cates the level of access to the system resources. In this way, there are four possible configurationsavailable: Secure privileged invasive debug, Secure privileged non-invasive debug, Secure user inva-sive debug, and Secure user non-invasive debug [7]. The invasive debug allows to halt the processor,examine registers and memory regions and if wanted allows to modify them. The Non-evasive debugallows to observe but not modify or control resources of the system. While the user debug mode isdesignated for the usual program execution state, the privileged debug mode is used to service inter-rupts, exceptions, and to access protected resources. In this way, the privileged debug mode can onlybe executed from the Secure World.

2.1.3 Software Architecture

In the previous subsection it was described the Hardware Architecture for the most common approach ofdeveloping a TEE. However, as the TrustZone is an open architecture, there is not a predefined softwarestack that should be used. Instead, any developer can implement their own version of the softwareenvironment to fit their needs. For example, instead of using the same core for the two virtual worldsas described, it is possible to have a dedicated processor just for the Secure World [7]. The softwarearchitecture for the TEE can also be simpler than indicated before. Instead of having a full dedicatedTrusted OS, one can use a synchronous library placed in the Secure World [7].

Although there is a certain flexibility available, there are some principles that every implementationshould take into account, more specifically, the software developed for the Secure World should be asminimal as possible to reduce the surface of attack and to occupy the least memory possible since it isa critical resource for some platforms; and, if a Trusted OS is implemented, it should provide a SecureBoot, which adds cryptographic checks to each step of the boot process to guarantee the integrity ofthe Secure World software, “preventing any unauthorized or maliciously modified software from running”[7].

A Software Architecture that has a full fledged Trusted OS, like the one presented in the Figure 2.1,could be considered one of the most powerful designs. With an operating system in the Secure World itis possible to have multiple independent TAs that don’t depend on the Normal World environment, andit also allows to have different memory spaces for each TA preventing any possible tampering amongsecure tasks [7].

For a better understating of how a CA could use a TA for the execution of a security service, takeas an example the Software Architecture presented in the Figure 2.1. When a security client that runson the common execution environment wants to perform an operation handled by a security service,it firstly invokes a command using the TEE Client API to allocate a region of memory that will contain

10

Page 27: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

the arguments of the operation, then it invokes another command through the same API to indicate thedesired operation and the reference of the memory region previously allocated. The Rich OS will in turn,use a driver to communicate with the Secure Monitor. Once in monitor mode, the processor automati-cally starts to execute the Secure World. It is then that the Secure Monitor stores the current executioncontext of the Normal World and restores the previously stored context of the Secure World. When thisis done the switching process is finalized. From this point on, the Trusted OS will use predefined entry-points to call the desired function of the respective security service through the TEE Internal API. Afterthe security service preforms the operation, the obtained result is written back in the memory regionindicated by the CA and where previously were the function arguments. The transaction to the NormalWorld is done following a similar process.

2.1.4 Security Features and Economic Impact

Some of the security features that result from the use of the TrustZone Technology were mentioned in theprevious subsections, namely, the possibility to: hide the access of critical peripherals from the NormalWorld; have a secure storage that is only accessible through the Secure World; perform cryptographicoperations and security services in a trusted manner by using TAs; mark certain regions of memoryand cache memories as secure to guarantee that the data processed in the TEE is not accessible tonon-trusted components; provide each TA with its own memory space that cannot be accessed by otherTAs or CAs; add integrity checks of the secure world software stack to avoid data tampering; providea Secure Boot of the Trusted OS to remove the possibility of modifying it while the device is turned off;restrict the debug range, which normally “has the potential to become a backdoor to security breachesonce the device is in production” [24].

With all these security features, it is possible to conclude that the attacks performed with the intentof tampering the TEE are impractical, as they imply a serious hardware investment [34]. In the sameway, boot attacks do not work either due the use of Secure Boot, and attempts to update the firmwarewill also be unsuccessful if they are not properly authenticated. The assets are also protected from themost common software attacks, as all the sensitive data and security tasks are processed in the SecureWorld.

However, there should always be given special attention to which applications are installed in theNormal World, as in the most common implementations of the TEE, the Central Processing Unit (CPU)is shared between the two virtual worlds so there is still a risk of side-channel communication fromuntrustworthy code [34]. The lab attacks, in which the attacker has access to sophisticated laboratoryequipment, are not considered in the protection provided by the TrustZone technology. Nevertheless, theTrustZone technology could be used in conjunction with the ARM SecurCore®, which is an architecturedesigned primarily for tamper-resistant smart cards that increases the security against physical attacksof the processor that implements that architecture [7].

From an economical point of view, ARM TrustZone technology is a relatively low cost solution whencompared with dedicated secure cryptological processors, as it allows a programmable environmentinstead of a unique solution. It also provides protection when the data is being processed instead ofjust providing the cryptographic functions. Moreover, if the Secure World runs on the main processorinstead of a secondary one, the TEE code will run faster and less silicon space will be used which willreduce the final cost of the product. One could also compare TrustZone with smart-cards, which areoften used due the strong security they can offer. Although this security can be considered better thanthe one provided by TrustZone, as smart-cards lack platform binding, that is, they do not include all thenecessary hardware to operate independently, they require additional specialized hardware to be used.This condition makes some applications infeasible to support [34].

11

Page 28: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

Overall, the financial impact of a TrustZone-based solution is low in terms of the added hardware andsoftware, but the provided level of security is very large, given the adopted design choices are correctlyadapted to the final application.

2.2 Bitcoin Protocol

The Bitcoin concepts and general architecture were first proposed in Satoshi Nakamoto’s publication [3],which in its core, defines how the Bitcoin currency is generated, how the transactions are performed, andhow the network that is based on prevents double-spending [35] without the need of a trusted third party.However, it is important to notice that it is very difficult to formally specify or structure the Bitcoin protocolbecause Bitcoin relies on a peer-to-peer network, and as such the protocol ends up being defined bythe group of nodes that have more computing power. Thus, whenever it is desired to improve Bitcoinfeatures or to amend possible problems with the system, Bitcoin Improvement Proposals (BIPs) [36]should be used. In a certain way, BIPs are similar to the Request for Comments (RFC) pages, sinceboth propose possible modifications within the community to attain improvements. The main differencebetween them resides in the approval process which is more restrictive for the former than the latter one.Nonetheless, any Bitcoin enthusiast has at its disposal a quite complete documentation that describesthe behavior of the original Bitcoin client developed by Satoshi Nakamoto [37]. From this point on, fora better understanding, the capitalized “Bitcoin” term will be used to refer to the protocol and generalconcept, and lowercase “bitcoin” will be used to refer to the correspondent digital currency.

2.2.1 Bitcoin Architecture

Bitcoin is heavily based on the concept of public key cryptography. Every Bitcoin user needs to have, atleast, one pair of cryptographic keys, where the private key is used to sign transactions and to accessthe funds stored in the Bitcoin address, which is essentially the correspondent public key. As a visualexample consider a money-box (public key) that is know by everyone and anyone can put money into it,but only the one who has the key (private key) to open it can remove the money that is inside.

Another concept that is greatly used in Bitcoin are digital signatures. As every transaction a usermakes is signed with the private key, it is created a digital signature that is used alongside with thepublic key to prove the authenticity of the transaction and to avoid tampering.

Whenever a transaction is performed and submitted into the Bitcoin network it goes straight to atransaction pool, and after a certain period of time, some nodes of the network start to aggregate thosetransactions into groups called transaction blocks. These nodes, also known as miners, usually verifythe validity of each transaction before inserting them into a block, and then they perform multiple crypto-graphic hashes of a transaction block until a certain condition is met, in order to create a proof-of-work[38]. A random nonce is introduced in each block, so that each hash of a block generates a differentvalue. If this hash is lower or equal than a predefined 256-bit number1, then the condition for the blockto be valid is fulfilled, otherwise the nonce is incremented until that happens. Once this condition is met,it is proven that the miner has spent some computing power to obtain the correct nonce that led to thefinal solution creating, in this way, a proof-of-work. Every 2016 valid blocks, the network checks howmuch time the miners took to process each block. The expected time is 10 minutes, and if the blockshave been processed faster, it means that the computational power was increased. When this happens,the difficulty of producing a proof-of-work is increased by reducing the target number.

Once the proof-of-work is done, the miners receive a reward for the effort, more precisely, theyreceive the bitcoins that are included in a transaction named coinbase. Every transaction block has

1This target number is usually called as difficulty (of generating a block), and is shared by all Bitcoin clients.

12

Page 29: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

only one coinbase transaction that is added by the network to reward the block miner and to createthe digital currency. This is how the bitcoins are generated and used as a motivator for the nodes toprocess transactions. In addition to the reward, the miners also receive any fees associated with everytransaction of the transaction block they processed.

In Figure 2.2 it is pictured a simplified diagram of the previous mentioned concepts and how theyinteract.

Figure 2.2: Simplified structure and flow of the Bitcoin architecture.

After a transaction block is mined, it is added to the end of a chain composed of previously processedblocks. This chain is denominated as blockchain and can be considered as a public ledger that recordsevery transaction of bitcoins that was ever made in chronological order. The ledger is stored in everycomputer node that supports the system creating, in this way, a decentralized structure that maintainsthe ledger: a transaction block after being verified and processed by a miner is broadcasted to the wholenetwork; the first receiving nodes perform some checks and then add the block to their own copy of theledger and pass along the transaction block to other nodes which will follow the same procedure. Thenode’s process of checking the received transaction block is the reason why the miners verify the validityof each transaction that they include in a transaction block. If there is an invalid transaction, the nodeswill ignore the block making all effort of the miner useless. Moreover, the miner would also not receiveany reward or fee, because the ignored block would not be included in the blockchain so it is the sameas it was never processed.

Some times it happens that two transaction blocks are mined at the same time. The nodes placeeach block in a separate branch of their copy of the blockchain, which makes it to temporarily have anadditional path. However, due network delays, the nodes receive one of the two transaction blocks firstand it is after the first received block that they continue to add new transaction blocks, increasing thatassociated path. The network nodes always accept the longest path of the blockchain as the correctone, discarding the blocks of the smaller path. This means that the transactions that were on the blocksof the smaller branches are placed back in the transaction pool to be included in new transaction blocks.Thus, after performing a transaction that is included in a mined transaction block, it is advised to waitfor a few transaction blocks to be processed and added to the blockchain to have the guarantee thatthe transaction was completed successfully and will not be discarded. This guarantee can be given,because each block that is placed in the blockchain contains the hash of previous block, and as the

13

Page 30: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

nodes always pass the blocks of the larger path, the receiver nodes will also converge to the same path.In Figure 2.3, a situation is depicted where a node receives the Block 75 and then the Block 74, as

both were mined at the same time and after the Block 73, they are placed in two different branches andlinked to the Block 73. Then, Block 76 is mined and broadcast to the Bitcoin network until eventuallyreaching the node. Once the block is there, and supposing that it extends the path associated with Block75, it is placed after it, ending up extending the branch length. From this point on, the path: Block 72=⇒ Block 73 =⇒ Block 75 =⇒ Block 76, is considered the correct one and the transactions that werein Block 74 are discarded and placed back in the transaction pool.

TransactionID = a7k9b...

TransactionID = bc6fc...

.

.

.

Block 72

Proof of work: 000000000000000002869...Previous block: 000000000000000003875...

TransactionID = 73aa2...

TransactionID = f840f...

.

.

.

Block 73

Proof of work: 000000000000000005721...Previous block: 000000000000000002869...

TransactionID = ee8b1...

TransactionID = cbe0a...

.

.

.

Block 75

Proof of work: 000000000000000002112...Previous block: 000000000000000005721...

TransactionID = bebc5...

TransactionID = w8mu...

.

.

.

Block 76

Proof of work: 000000000000000008732...Previous block: 000000000000000002112...

TransactionID = 02201...

TransactionID = c3cef...

.

.

.

Block 74

Proof of work: 00000000000000000d955...Previous block: 000000000000000005721...

Time

Figure 2.3: Example of a fork in the blockchain.

This public ledger is the core of Bitcoin, and to comprehend why this is, it is important to reallyunderstand what bitcoin is. Until now, bitcoins were referred to as the digital currency of Bitcoin, andin fact, there is not a single digital file or a physical object that can be pointed out as being a bitcoin,instead “they exist only as records of transactions” [39]. Thus, it is not possible to known the balanceassociated with a specific Bitcoin address just by counting the bitcoins that there are there because theysimply do not exist. To verify if a user has enough balance to perform a transaction it is needed to gothrough the transactions that have the user’s Bitcoin address as the sender or as the receiver, and verifythe amount of bitcoins the user has received that have not yet been spent.

As there is a public ledger that everyone in the Bitcoin network has access to and has all the trans-actions ever performed, the miners make use of it when verifying the validity of a transaction. As thetransaction blocks are introduced in the chain as they are processed and each of them contain the hashof the preceding block, it is created a chronological order of transactions that together contain a largeamount of work, and as long as the majority of the computational power is not controlled by cooperatingnodes that intend to attack the network, the double-spending problem is avoided without the need of athird party because it is formed “a record that cannot be changed without redoing the proof-of-work ” [3].

2.2.2 Bitcoin Addresses

A Bitcoin address can be seen as a bank account in the way it works: if a user wants to transfer somebitcoins he just needs to know the destination Bitcoin address. However, there are a few differences and

14

Page 31: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

one of them is in the way that Bitcoin addresses are generated which is custom designed and does nothave any cost associated. There are some cryptographic operations that back up this generation pro-cess, namely, i) Elliptic Curve Digital Signature Algorithm (ECDSA) [40], ii) SHA with 256 bits [41], iii)RACE Integrity Primitives Evaluation Message Digest (RIPEMD) with 160 bits [42], and Base58Checkencoding [43].

Previously, it was mentioned that a bitcoin address is based on a public key from a cryptographickey pair: here is where the ECDSA takes place as it is used to generate the public key. ECDSA, asthe name indicates, is a variant of the Digital Signature Algorithm (DSA) [40] which uses Elliptic CurveCryptography (ECC) [44] to generate cryptographic key pairs, sign messages, and verify the signaturesof already signed messages. The ECDSA curve used in Bitcoin is defined by secp256k1 parameters[45, 46], which translates into the y2 = x3+7 equation. The public key consists of a point in the specifiedcurve, and as such the format used in the generation process is the concatenation of the X and Y

coordinates of the selected point. To this public key representation it is added one leading byte whichindicates the state of the public key, namely if it is in a compressed (0x02 or 0x03) or uncompressed(0x04) form. While in the former state the representation is 32 bytes long, in the latter state it is 64 byteslong. At this moment, there are 65 or 33 bytes to represent a Bitcoin address but the ideal should beto have, at most, 20 bytes which would be attainable using the RIPEMD with 160 bits. However, due tounexpected interactions between RIPEMD and ECDSA a weakness might be created [47]. To mitigatethis issue an intermediate hash algorithm, SHA with 256 bits, is used to create a key hash with 32 bytes,and the RIPEMD with 160 bits is used reducing the key hash to 20 bytes long.

Besides the main Bitcoin network where the blockchain is inserted, there is a testing network [48]that uses an identical process to generate Bitcoin addresses. Thus, to identify the type of network forwhich the address was created, an additional byte is used corresponding to the main network (0x00)and the test network (0x6f ).

The Bitcoin address generation process also takes into account the possibility of a user entering anincorrect addresses by mistake. To avoid those situations a 4 byte long checksum is used that resultsfrom the truncated double-SHA with 256 bits of the network identifier byte concatenated with the keyhash. The reason why two iterations of the SHA with 256 bits are used instead of one lies in the factthat the algorithm’s design is similar to the SHA1 for which the resistance against birthday attacks hasbeen partially broken [49]. At the moment, the SHA with 256 bits is not susceptible to such attacksbut performing a double hash hardens its resistance, making this, in fact, a measure against futurecryptanalytic developments [49].

The process to generate a Bitcoin address is almost complete, and the only thing that remains todiscuss is the representation of the final 25 bytes (1 byte of the Network ID, 20 bytes of the key hash and4 bytes of the checksum). As most of the times the user inputs the destination Bitcoin address with akeyboard, an alphanumeric representation is a good option. A first approach would be to use a Base64encoding. However, it has some symbols that can appear visually identical: “0” (zero), “O” (capital o),“I” (capital i), and “l” (lower case L); it also has two non-alphanumeric characters: “+” (plus), and “/”(slash). As a second alternative, there is the Base58Check encoding which is the same as base64 butit does not include the previously mentioned symbols becoming a better solution and the one currentlyused. Therefore, the 25 bytes long Bitcoin address is represented by 26-34 alphanumeric characters ina more user-friendly manner. The shorter addresses result from the fact that they start with zeroes andas the zeroes are not encoded the address representation gets shorter.

The whole process here described is summarized in Algorithm 1 and is instantiated in Example2.2.1 for an uncompressed public key and to an address destined to the main network.

15

Page 32: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

Algorithm 2.1: Bitcoin Address Generation [50]. In the equations the _ operator represents con-catenation.Public key ← ECDSA-secp256k1( X _ Y );V ersion← 0x02

∨0x03

∨0x04;

Key hash← RIPEMD-160[ SHA-256( V ersion _ Public key ) ];Network ID ← 0x00

∨0x6f ;

Checksum← ( SHA-2562[ Netowork ID _ Key hash ] )[0 : 3];Bitcoin address← Base58CheckEncode( Netowork ID _ Key hash _ Checksum )

Example 2.2.1 Example of Bitcoin address generation [50]

Public key ← 50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2

3522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6;

V ersion← 0x04;

Key hash← 010966776006953D5567439E5E39F86A0D273BEE;

Network ID ← 0x00;

Checksum← D61967F6;

Bitcoin address← 16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM

From Algorithm 1, it is easy to notice that the amount of possible Bitcoin addresses is limited bythe RIPEMD with 160 bits. The key hash is always 160 bits long which means there are 2160 or about1, 460, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000 different possible addresses. Iftwo different persons accidentally generate the same public key (Address Collision), it means that bothof them also have the corresponding private key and as such can access and steal the funds from eachother, however, “it is more likely that the Earth is destroyed in the next 5 seconds, than that a collisionoccur in the next millenium.” [50, 51].

2.2.3 Bitcoin Transaction Process

Bitcoin supports different types of transactions, but the one that is most used is the Pay To Public KeyHash (P2PKH) [52]. As the name says, in this type of transaction the payment recipient is representedby a hash of the public key, just as it was described in subsections 2.2.1 and 2.2.2. As this is thestandard type, it is the one that is considered in this dissertation.

A transaction message embeds some constant values, an array of inputs, and one array of outputs[52]. The constant values are: i) the hash of the transaction message, that is used as the transactionidentifier; ii) the format version of the transaction message; iii), iv) the length of the inputs and out-puts array, v) the locktime which indicates the earliest time or earliest block when the transaction maybe added to the block chain, and vi) the size of the transaction message in bytes. The outputs areinstructions for sending bitcoins and are composed of two fields: i) a value, that indicates the amountof bitcoins to send, and ii) a ScriptPubKey which is the “locking script that determines the conditionsthat need to be met in order for a transaction to be spent” [53]. The inputs are references to outputsfrom previous transactions and are composed of three fields: i) the transaction identifier of the referredoutput, ii) an index that specifies the output in the outputs array of the referenced transaction, and iii) aScriptSig which is the “is the unlocking script that solves the conditions placed on the transaction by theScriptPubKey ” [53]. An output is considered as “unspent” until it is referenced by an input in a transac-tion, once this happens it is considered “spent” and can not be referenced ever again by another input[52].

There is a rule in Bitcoin transactions that must always be verified, that is that in a transaction the

16

Page 33: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

total amount of bitcoins in the inputs array must match the total amount of bitcoins in the outputs array.This means that if the total input amount is greater than the payment amount plus the transaction fee,the user should introduce an additional output to send the remaining bitcoins back to him. The outputused to this end is called change.

In Figure 2.4, a simplified example of a Bitcoin transaction is represented, where the paymentamount is 13.0 bitcoins. To achieve this value, one or more inputs are needed with referenced outputstotaling at least the desired amount. This way, the current transaction uses two inputs, one that points toa coinbase transaction and references the output with index = 0, and another that points to a previoustransaction that is stored in the blockchain and references the output with index = 1. The total inputamount totals 13.8 bitcoins (12.5 + 1.3 = 13.8) and the transaction fee is set to 0.5 bitcoins, whichleads to a change of 0.3 bitcoins (13.8 − 13.0 − 0.5 = 0.3) that are sent back to the sender. Once thecurrent transaction is added to the blockchain, the outputs that were referred by the used inputs are nowconsidered “spent” so they cannot be used again in future transactions.

Coinbase transaction

OutputValue=12.5

scriptPubKey

ID = 90b18...

ID = 72c5b...

InputID=6f5c1…

Index=0SigScript

OutputValue=2.5

scriptPubKey

OutputValue=1.3

scriptPubKey

Output (fee)

Value=0.03scriptPubKey

ID = ff1ab...

InputID=90b18…

Index=0SigScript

OutputValue=13.0

scriptPubKey

Output (change)

Value=0.3scriptPubKey

Output (fee)

Value=0.5scriptPubKey

InputID=72c5b…

Index=1SigScript

Input BTC=13.8

Output BTC=13.8

Current Transaction

Previous transaction in blockchain

Figure 2.4: Simplified Bitcoin transaction example.

An important aspect that remains to mention regarding Bitcoin transactions is the signing process.To digitally sign a transaction message the ECDSA with the secp256k1 curve specifications is used.However, in Bitcoin this process cannot be based in the traditional approach of creating a private key, useit to sign the transaction message and thus produce its digital signature; because the digital signature isincluded in the transaction message itself. Hence, instead of using the whole message as the subject ofthe signature, all inputs included in the transaction message are signed, which in turn will be embeddedin the correspondent ScriptSig. This script will include besides the signature, the public key (Bitcoinaddress) that matches the hash given in the ScriptPubKey of the redeemed output.

After this signing process, the transaction is broadcasted to the Bitcoin network where peers validateit before transmitting it further, and miners validate it before including it in a new transaction block. Thevalidation process consists in evaluating inputs’ ScriptSigs and the referenced outputs’ ScriptPubKeys.By adapting the two scripts, the sender can create different types of conditions that the receivers haveto meet in order to receive the payment. For example, the ScriptPubKey can define that the transactionrecipient could be anyone, or can also require that in order to spend the bitcoins an input must be signedwith private keys that belong to different people [52].

17

Page 34: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

Public Key: 0438c73f3ba716a2b214141da57eb60f6fdbe8652bb5a05944010087a51460a16dcdad7bf71608e0cba3125d00c94656c18b130150bd92cbc1ea

a73fd266b04c85

Signature:3045022100c51d512928e13d61a30ceb77db70e5d0b565d559f5491edb7cf2312ae84ae06f022050f0710d436a6dc8bf415dc3b86c7b66b0be534

2e257b86cb5fcb203f693632801

ScriptSig

ID = 13aaf...

InputID=84c24…

Index=0SigScript

OutputValue=0.0015scriptPubKey

Output (fee)

Value=0.0000258scriptPubKey

Recent Transaction

Output (change)Value=0.0000512

scriptPubKey

ID = 84c24...

InputID=5e7ca…

Index=0SigScript

OutputValue=0.001577

scriptPubKey

Output (fee)

Value=0.0002scriptPubKey

Previous Transaction

OutputValue=0.00159956

scriptPubKey

InputID=d264e…

Index=2SigScript

OP_DUP OP_HASH160

Hash160: 980c312d019510eac5c25715a97ae

1732f395302 OP_EQUALVERIFY

OP_CHECKSIG

scriptPubKey

Sent to the address=1ErxK...

Figure 2.5: Example of real Bitcoin transactions with some information about the scripts used [54, 55].

For a better understanding of how the validation process is made and which information is containedin the ScriptSig and ScriptPubKey, take as an example the Figure 2.5 where two real transaction thatare stored in the blockchain are presented. One of the Previous Transaction output, in the amount of0.001577 bitcoins, is destined to the user that generated the Bitcoin address=1ErxK.... This output islater referenced by an input in a more Recent Transaction. When a miner or a peer verify the RecentTransaction validity, they use the input’s ScriptSig and its referenced output’s ScriptPubKey. The contentof former script is the Signature and the Public Key, and the content of the latter script is the sequentialoperations that must be used in order to verify that the output can be used. The verification proceduremakes use of a last-in first-out (LIFO) stack to store the arguments of the operations, each operationremove the first items of the stack and stores back the result. In the case of Figure 2.5, the Signatureand then the Public Key are first stored in the stack. Afterwards, the Public Key is duplicated (OP_DUP)and its hash is performed (OP_HASH160). The next item on the ScriptPubKey is not an operationbut a hash (Hash160), and as such it is also placed in the stack. The following operation is to verify(OP_EQUALVERIFY ) if the first two items on the stack are equal, if so it is proven that the RecentTransaction is performed from the address that the output was destined to. Lastly, the only items thatare left in the stack are the Signature and the Public Key, which are used to verify (OP_CHECKSG) ifthe input was signed with the correspondent private key.

2.2.4 Bitcoin Wallets

Up to this point, it is possible to infer that the processes of generating addresses, signing transactions,and checking the balance are some of the Bitcoin core processes. With this in mind, Bitcoin walletswere created to assist in and handle the execution of those processes. A Bitcoin wallet is a digital walletanalogous to a physical wallet, but instead of storing currency, it stores all the private keys associatedwith the generated Bitcoin addresses, signs transactions, and consults the blockchain to inform of theavailable funds in each address. However, as with physical wallets, there are different types wallets

18

Page 35: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

available to fit different needs as shown in Table 2.1. In this way, some of the main functions may bedisabled due to their nature and others may be added.

Every type of wallet can be categorized as a hot wallet or a cold wallet. Whereas hot wallets aremeant to be used on a daily basis, and thus are typically connected to the Internet for a faster andmore convenient use, cold wallets remain offline for less exposure and are used for long-term storageof large amounts of bitcoins. For example, a Light Desktop Wallet is a hot wallet as it needs to accessthe blockchain for everyday use. Hot wallets are not very secure, since their connection to the Internetmakes them quite susceptible to a variety of attacks. On the other hand, the Paper Wallet correspondsto a cold wallet, because it is just a piece of paper where a key-pair is printed on. Cold wallets are verysecure but lack usage flexibility, and thus are more recommended for storing large amounts of bitcoins.The Hardware Wallet is a cold wallet that has the best security/functionality ratio of all the wallet types[56]. It is a dedicated piece of hardware that provides increased security features, and it is capable notonly of storing private-keys in the long-term but also of signing transactions offline.

Although the use of Bitcoin wallets take some responsibility from the Bitcoin users, they still have totake certain precautions. The wallets that generate Bitcoin addresses store the correspondent privatekeys, and this means that if those keys are lost so are the corresponding bitcoins. To avoid this kindof situations, the user must do regular backups of the private keys. In February 2012, the BIP 0032[57] was introduced that described an additional functionality to Bitcoin wallets, where it was added thepossibility to generate multiple private keys, and consequently different Bitcoin addresses, from one seedwith a given deterministic derivation rule. The wallets that implement this functionality are denominatedHierarchical Deterministic (HD) wallets. Thus, the user could create different Bitcoin addresses throughan algorithm that, if it is given the same conditions, would always generate the same addresses. Thisallowed the user to do just a backup of the seed instead of all the private keys that are used as they canbe generated again from the seed.

Table 2.1: Main types of Bitcoin Wallets.Type Description Characteristics Most Known Wallets

BitcoinClients

The host of the wallet becomesa full node of the Bitcoin net-work, which means that thewhole blockchain is downloadedand kept locally.

- Initial setup takes a long time due the largesize of the blockchain;- Private keys are stored on the host givingmore control over the bitcoins.

- Bitcoin Core [58].

LightDesktopWallets

Operates in a similar manner asthe Bitcoin Clients but it does notdownload the full blockchain.

- Setup is relatively fast;- Private keys are stored on the host givingmore control over the bitcoins.

- Multibit [59];- Electrum [60];- Armory [61].

OnlineWebWallets

A third party stores the privatekeys in their servers which areaccessible through an accountcreated for their services.

- Entrusts the security to the service providerwho has full control over the client’s bitcoins;- Flexible as most of them have mobile anddesktop versions available.

- Coinbase [62];- Xapo [63];- blockchain.info [64].

MobileWallets

Used in mobile devices. It couldbe an application that works asa Light Desktop Wallet or as anOnline Web Wallet.

- The most convenient wallet;- Can have enhanced features: use of QRcodes and NFC.

- Bitcoin Wallet [65];- Mycellium [66];- Copay [67].

PhysicalWallets /PaperWallets

A piece of paper that has the pri-vate and public keys printed on.

- Can easily be generated from different web-sites;- Does not allow to consult the balance ontheir own;- Could be very secure if well protected.

Most used website to gen-erate this type of wallet:https://www.bitaddress.org/

HardwareWallets

A secure hardware device is re-sponsible for the generation andstorage of keys and the signingprocess.

- Very secure;- Does not allow to consult the balance ontheir own;- Resistant to computer viruses.

- Ledger Nano [68];- KeepKey [69];- Trezor [70];- BitSafe [71].

19

Page 36: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

2.2.5 Security Features

The Bitcoin protocol has in its implementation some considerations regarding the security and privacyof its users. For example, when performing a transaction if the destination address is not transcribedexactly and becomes invalid, it is likely that the transaction will be rejected. In fact the possibility ofthat not happening is approximately 1 in 4.29 billion [72]. However, if by chance the mistyped addressalready exists, then the transaction is considered valid and once that is broadcasted to the network itcannot be reversed.

One important characteristic of Bitcoin that affects both the security and privacy of its users is theblockchain. The fact that this ledger is publicly available gives the users and merchants more securityagainst frauds, like identity theft or credit card fraud. However, as the ledger is stored permanently onthe network some effort is required to protect the privacy of the users. Even though Bitcoin addressesdo not reveal any kind of information about the user, it is still possible, given a address to deduct thepurchase history by analyzing the blockchain. For that reason, it is advised to use a Bitcoin address onlyonce, and when performing a transaction the change should be redirected to a new address generatedby the user. This way, it is much harder to trace back the addresses through the available transactionsto a user.

Due the critical role that Bitcoin wallets have, the user should be very careful when choosing one.There are some wallets that are more fitted for long term storage and others that should be preferred fora every-day use. The increase of flexibility of a wallet usually conditions the security that it provided, forexample, a Online Web Wallet has a very flexible usage but as the private keys are entrusted to a thirdparty they have complete control over the client’s funds.

Finally, it is important to understand that Bitcoin is not completely anonymous as the servers can tryto associate the Internet Protocol address to the data requested in the network. Despite all the protectionthat Bitcoin offers, ultimately the level of security and privacy provided depends on the good practicesadopted by the user.

2.3 Related Work

As the TrustZone is a low-cost solution for the level of security it provides, it has been used for allkind of payment services and systems. It has been exploited to create a framework that would allowany application to use a privacy friendly online remote prepaid payment system while guaranteeingthat its user’s sensitive data is protected [73]. To that purpose, it was taken advantage of the secureenvironment provided by the TrustZone to handle the security sensitive operations and to store theprivate data. Another system that was proposed and relied on the TrustZone secure storage, consistedin a mobile ticketing system that offered an additional security layer over the recipients stored on devicesleading to a more trusted proof of purchase [74].

Recently, TrustZone has also been considered for the improvement of Bitcoin Mobile Wallets, butno experimental results or security analysis have been provided [75, 76]. In 2014, Rivetz®, a companythat is focused on providing solutions that are used as an intermediate layer between the hardwaresecurity that is built-in the devices and the application developers [77], started to develop a standard APIwhich would be used with a TA to perform certain security operations, create a trusted user interface,and securely display transactional data [75]. In mid 2015, Rivetz released the API allowing third-partyBitcoin wallet providers to use it in their applications [78].

Still in 2015, Ledger®, an Hardware Wallet manufacturer [79], developed a similar concept that con-sisted in virtualizing a Hardware Wallet into a mobile device to make use of its TrustZone-enabled pro-cessor [76]. The goal was to develop a TA that provided the same level of security as an Hardware Wallet

20

Page 37: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

and through an API it could be integrated in Mobile Wallets. This TA would make use of the secure stor-age, trusted user interface, and perform cryptographic operations. In early 2016, an application, named“Ledger Trustlet”, was released for some Android platforms [80] alongside with a Software DevelopmentKit (SDK) [81].

The two previous solutions are quite similar, the one proposed by Rivetz is more general and ise-commerce oriented while the one proposed by Ledger is more specific to Bitcon and thus it couldalso be more efficient. Both of them use the same TEE implementation, <t™-base TEE, developed byTrustonic®, a company that provides development platforms for trusted devices [82]. However, to usethis TEE one has to pay license fees to its developers, which, in turn, will be reflected on the price of thefinal product. Moreover, besides the license it is needed a platform that has <t-base TEE by default, andfor each of those devices one needs to develop specific drivers. These conditions restrain the numberof platforms where the presented solutions can be employed and, at the moment, the Rivetz SDK iscompatible with only seven different Android phones while the Ledger trustlet can only be used in five.It is important to notice, as described in Table 2.1, that Mobile Wallets can have its private data storedin the service provider servers, which means that, even by using the TrustZone technology availablein a mobile device, the security of the private keys might be compromised. For example, it has givenblochain.info as an example of an Online Web Wallet. However, this wallet also provides an mobileapplication, which makes it also a Mobile Wallet. In any case, blochain.info does not allow to close anycreated account, which means that there is not the possibility of erasing any wallet and the associatedprivate data from their servers. If for some reason the servers become vulnerable, the data even ifencrypted can be compromised.

Another important aspect is the TEE itself. For example, Qualcomm’s Secure Execution Environment(QSEE), a TEE implementation developed by Qualcomm®, is widely deployed among Android devices,and recently a vulnerability has been discovered in its software, where an “attacker running code in theNormal World could take advantage of a vulnerability in mediaserver to exploit an application runningin the Secure World. Then the attacker could modify the Normal World’s Linux kernel, allowing theattacker to compromise the whole operating system to whatever ends they’re trying to achieve” [83].Thus, it is also important to guarantee that the software which the solution is based on is well tested andscrutinized, and open-source software could help to achieving that since it is more readily available forscrutiny by the scientific community.

In sum, the existent work tries to be an intermediate layer between the TrustZone-enabled processorof a mobile device and a Bitcoin Mobile wallet that is installed in the same device. Their main goal isto add to flexible wallets more security by developing APIs and TAs that could be integrated in existingsolutions. The work proposed in this dissertation tries, instead, to implement a Bitcoin wallet that makesdirect use of a TrustZone-enabled processor. The main goal is to increase the security of one of the mostsecure wallets (hardware wallet) while, at the same time, providing more flexibility than the available,bearing in mind in every step, to opt for open-source software and develop code to attain a platform-independent solution. Furthermore, in contrast to the previous TrustZone Bitcoin solutions, a securityanalysis is herein provided, alongside experimental results.

2.4 Summary

In this chapter, TrustZone was presented, which is an ARM security extension based on the concept oftwo distinct virtual worlds that are executed in parallel and have different visions of the SoC. There is aNormal World and a Secure World. Whereas the former is the usual common execution environmentwhere the generic applications run, the latter is a TEE where TAs are executed with exclusive accessto memory regions and peripherals marked as secure. Some generic applications, known as CAs, can

21

Page 38: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

request TAs to perform security sensitive operations. Both applications have the possibility of exchangingdata through shared regions of memory.

Bitcoin was also introduced, corresponding to a peer-to-peer network that allows to perform transac-tions from one user to another, without the need of a trusted third party to prevent the double-spendingproblem. To achieve this feature, an ongoing chain of transactions is used, where transactions areinserted in a chronological order after providing a proof-of-work. In this way, a ledger is created thatcontains all the transactions ever performed that cannot be changed without redoing all the proof-of-work associated with the same transactions. Some important aspects of Bitcoin were discussed withmore detail, such as the process of generating Bitcoin addresses, the transaction process itself, and thedifferent types of available Bitcoin wallets.

Finally, the existent work was described. As the features of TrustZone are very attractive to paymentservices, it has already been used to create a privacy friendly online remote prepaid payment framework[73], and a mobile ticketing system that provided more security to the recipients stored on devices [74].Recently, TrustZone has also been considered for the improvement of Bitcoin Mobile wallets [75, 76],but no experimental results or security analysis has been provided. Rivetz and Ledger are the twocompanies that have invested in this area by developing SDKs that could be used alongside with TAs toimprove the security of the existent Bitcoin Mobile Wallets.

22

Page 39: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

CHAPTER 3

PROPOSED TRUSTZONE-BASED

BITCOIN WALLET

Contents

3.1 Available Base Wallets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

3.2 Base Wallet Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

3.3 Proposed Improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

23

Page 40: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

In this chapter, it is proposed the use of a TrustZone-enabled platform as a Bitcoin wallet. Thepractical interest of such proposal arises from using the secure storage to store sensitive data, and fromtaking advantage of the reliable secure cryptographic services provided by the Secure World to performsome of the Bitcoin functions. First, the secure storage prevents certain attacks which are possible tooccur on other type of wallets, where a client’s password is used to encrypt private information [11].Since the TrustZone-based wallet encrypts the stored data using a key that is only available at thehardware level, no dictionary attacks are possible. The usage of the cryptographic services providedby the Trusted OS, that were developed by cryptographers with high expertise, also mitigates possibleside-channel attacks. Another benefit of this configuration is the integrity check that can verify if a pieceof the wallet’s code has not been tampered with and verify if the Trusted OS is unaltered before booting,preventing in this way, any unauthorized or maliciously modified software from running [7]. The TEE canassign different, secure, and exclusive regions of memory to different TAs, which creates the possibilityof running multiple security sensitive applications on the same device, such as those used for home-banking, since they will not interfere with each other.

In the following sections, the Bitcoin wallet that will be used as a base for development will be chosen.Then, a description of the same will be provided, where its main modules will be presented, which willallow to identify more easily possible points of improvement. Lastly, based on the previous description,techniques that can improve the base wallet security through the use of the TrustZone will be proposed.

3.1 Available Base Wallets

The process of choosing a wallet that will be used as a base for the TrustZone-backed wallet is dividedin two steps: the first step consists in analyzing the existent types of wallet to find the one more proneto benefit from the use of the TrustZone features, and in the second step a base wallet will be chosenaccording to the type selected in step one.

The main types of wallets that are available on the market were already introduced in the subsec-tion 2.2.4, and through a more careful analysis of Table 2.1, it is possible to conclude that there are twotypes of wallet that stand out from the others: i) Mobile Wallets due their usage flexibility and completefunctionality; ii) and Hardware Wallets due their increased security.

As it was previously mentioned, Mobile Wallets are applications that can be installed in mobile de-vices, from where they connect to the Internet to provide more functionality like checking the addressesbalances and broadcast the performed transactions. This type of wallet can be considered the mostflexible type of wallet as it offers a wide range of operations and is available for different operating sys-tems. However, security-wise it is not that strong because the private keys, most of the times, are storedonline or on the cloud of some service provider. In contrast, Hardware Wallets, being cold wallets asmentioned in the subsection 2.2.4, are one of the most secure types of wallets, since they consist ina isolated piece of hardware designed to store private data and sign transactions in a secure manner.However, to guarantee this increased security the wallet’s functionality is affected as it still needs a thirdparty software to check the balance associated with an address and to broadcast the transactions to theblockchain.

Taking into consideration all the characteristics referred, the type of wallet that will benefit the mostwhen integrated into a TrustZone-enabled platform is the Hardware Wallet, because it will not only allowto increase even more the security and trust upon the data processed and stored in the device, but itwill also enable a trusted execution environment which other applications that require the same levelof security can make use of, extending, in this way, the flexibility of this type of wallet and creating amore complete solution almost similar to the one provided by Mobile wallets. The fact of not having thepossibility to check the balance on its own could be mitigated with this solution, as the wallet could be

24

Page 41: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

easily expanded to check the blockchain when connected to a hosting computer that is online. Thus, theneed to carry an hardware device becomes a minor trade-off for the level of security that is provided.

After determining the type of the wallet, it remains to chose the base wallet itself. All the examplesof Hardware Wallets given in Table 2.1 were effective candidates as a base for development, so thenext step consists in comparing them. This comparison should be seen as an extension to section 2.3,where related hardware wallets are described in more detail. The reason why all of these wallets wereconsidered resided in the fact that Trezor and Ledger Nano are the most popular Hardware Wallets inthe market, KeepKey is the most aesthetically pleasing, user-friendly and has support for more thanone type of digital currency, and lastly BitSafe is a Hardware Wallet that started as a small open-sourceproject within the Bitcoin community and ended up being commercialized by a company called ButterflyLabs®, and despite not being yet available in the market there is a great interest in the product from theusers side [84, 85, 86, 87]. As the final version of BitSafe is not yet available, in this work the developmentprototype will be considered, which was greatly discussed and disclosed in a Bitcoin related blog [87] byits original creators. In Table 3.1 it is given a brief description about each one of the referred HardwareWallets as well as its strengths and weaknesses. Whenever possible the available specifications andthe base price are presented.

Table 3.1: Main Hardware Wallets.HardwareWallet

Description Features Advantages Disadvantages Specifications BasePrice

Trezor[70]

A small device with ascreen and on-boardbuttons that allow todisplay and confirmtransactions. Provides aweb interface to checkthe balance and insertthe transaction into theblockchain. It is one ofthe most popular andused Hardware Wallets.

- HD wallet;- The seed consists in 24 En-glish words randomly gener-ated;- Requires a PIN code forspending bitcoins. Incorrectguesses increases the waittime between guesses by apower of two;- To the seed can be added a25th word defined by the user.

- Screen and buttons offer ex-tra protection and verification;- Web interface that enablesstandalone operation;- Open-source [88] (License:GNU LGPLv3 [89]).

- Relatively expensive;- Need of a USB cableto connect the deviceto the host computer.

- Released inAugust 2014;- Processor: ARMCortex-M3 core(120 MHz) withcustom developedsystem;- Internal entropysource.

$99

KeepKey[69]

A very simple designeddevice that support mul-tiple digital currencies.It has a screen and aon-board button to dis-play and confirm trans-actions before signingthem. It was originallyforked from the Trezorproject.

- HD wallet;- The seed can be 12, 18 or 24English words randomly gen-erated;- Requires a PIN code forspending bitcoins.

- Simple usage, user-friendlydesign, and metal body;- Screen and buttons offer ex-tra protection and verification;- Support for multiple digitalcurrencies;- Open-source [90] (License:GNU LGPLv3 [89]).

- Relatively expensive;- Not as easy to trans-port as the alternativeproducts due the de-vice dimensions;- Need of a USB cableto connect the deviceto the host computer.

- Released inSeptember 2015;- Processor: ARMCortex-M3 core;- Internal entropysource.

$99

Ledger Nano[68]

A very affordable Hard-ware Wallet imple-mented on a smartcardwith a format similar toa flash-drive. It is oneof the most popular andused Hardware Walletsdespite the need of athird party software to beused.

- HD wallet;- The seed consists in 24 En-glish words randomly gener-ated;- Requires a PIN code forspending bitcoins. Three in-correct guesses will wipe thedevice;- Provides a security card asa 2-factor authentication to beused when performing trans-actions.

- Accessible price;- Small and convenient for-mat;- Security card to compen-sate the lack of a screen;- Integrated USB connectionto the host computer;

- Not as user-friendlyas the other options;- Cannot verify theoutgoing transactionsas it lacks a screen;- Requires a privateor trusted computer tosetup the wallet;- Requires Chromebrowser to be used;- Not fully open-source.

- Released inDecember 2014;- Microproces-sor inside a CCEAL5+ [91] smart-card;- Internal entropysource.

$39

BitSafeDevelopmentPrototype[87]

A practically platform-independent implemen-tation of a minimal Hard-ware Wallet in smallform factor. It hasa screen and on-boardbuttons to display andconfirm transactions andsensitive wallet opera-tions. It also provides abasic application to sendthe transactions to theblockchain.

- HD wallet;- The seed is randomly gener-ated and can be displayed in aencrypted form;- Requires confirmation for ev-ery sensitive operation;- Possibility to encrypt everywallet;- Possibility to have hiddenwallets which existence can-not be confirmed without thecorrect encryption key.

- User-friendly format;- Screen and buttons offerextra protection and verifica-tion;- Source-code practicallyplatform-independent;- Provides a basic applicationthat enables standaloneoperation;- Integrated USB connectionto the host computer;- Open-source [11] (License:BSD 2-Clause [92]).

- Still a prototype;- Seed is displayed asa byte array.

- Released inMarch 2013;- Internal entropysource.

N/A

25

Page 42: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

There are three main criteria that will be taken into account when selecting the base wallet: i) thepossibility of modifying the firmware, which translates into providing the source-code as open-source;ii) the device’s processor, and last but not least, iii) the level of the source-code dependency on theplatform where the wallet is implemented.

These selection criteria were chosen taking into account that what is expected from a base walletis the possibility to enhance its security through the use of TrustZone, and at the same time increaseits flexibility. Therefore, in order to make use of the TrustZone security features some changes into thebase wallet functions are needed, and to have that possibility it is necessary that the source-code ofthe base wallet is made publicly available and that its license allows modifications to it. The HardwareWallet processor is also an important factor as it is needed a processor with the TrustZone technologyenabled, or a base wallet whose hardware and firmware source-code are publicly availably so that it canbe ported to another platform that has a TrustZone-enabled processor. In this way the second criteriais not critical but rather convenient. The last criteria is based on the level of dependency that the walletsource-code has on the platform where it is deployed, which is a very important factor as, herein, in thisdissertation, it is intended to provide, in the end, a platform-independent solution.

With the essential information on the possible candidates for the base wallet summarized in Table 3.1,each option can be evaluated individually in order to find the one that best identifies with the selectioncriteria. Starting by analyzing the Trezor wallet, it can be observed that it has very good security mea-sures: increasing the waiting time between PIN guesses by a power of two makes brute force attacksinfeasible, using a seed composed by twenty-four common English words decreases the probability oferror in its typing and makes the seed representation more user friendly, and the possibility of adding atwenty-fifth word defined by the user gives more protection in case of the device being stolen togetherwith the seed. Practically everything related with Trezor is open-source [88], but it was developed specif-ically and optimized for the platform that is implemented on. The platform integrates a processor with anARM Cortex-M3 core [93] which, unfortunately, does not implement the TrustZone technology, and asthe developed source-code has a considerable level of dependence on the same platform the processof porting it becomes more cumbersome.

As the source-code of the KeepKey Hardware Wallet was initially forked from the Trezor project mostof its security features and characteristics are the same. The main difference between them lies in thedesign: while KeepKey has a more robust, steady and user friendly design, Trezor has a more fragileconstruction. However, as Trezor has been on the market longer than KeepKey, it is considered moresecure due to the large number of users and Bitcoin enthusiasts that have tested the device.

The Ledger Nano is a Hardware Wallet that is very popular in the market, and it is one of the mostused mainly due the its low commercial price. Like Trezor and KeepKey it displays the seed in 24common English words and requires a PIN code for spending bitcoins. The main difference is that inthe event of three consecutive incorrect guesses of the PIN code, it erases the entire memory of thedevice as a precautionary measure. As a way to address the lack of a display, it is provided a securitycard that is used as a 2-factor authentication for confirming transactions. However this measure doesnot protect against mis-indicated output transactions as without a screen it is not possible to confirmthat the amount of the transaction is correct. This Hardware Wallet requires a trusted computer to besetup and a Chrome browser to work, which are its main disadvantages. Moreover, for a everyday useit would require the user to always carry the security card along with the wallet. As a final remark aboutthis wallet, it is not open-source so there is not any chance to make any kind of modifications to itssource-code nor to port it to another platform.

The last candidate for the base wallet is the development prototype of the BitSafe Hardware Wallet.This prototype was made available before the other candidates were released so while it may not havesome of the other candidate’s security features, it is considerably secure. It has the option to display

26

Page 43: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

the seed in an encrypted form so if the seed is stolen it becomes useless without the decryption key.All the sensitive operations require user confirmation which is granted by pressing a button locatedon the device, and the most critical operations like formating the wallet also require the introductionof a PIN code. A very good characteristic that this wallet has and which makes it stand out is itsplatform-independent code, which facilitates the porting process of its source-code to a different platform.Unfortunately, there is not any published information about the processor used on the final developmentprototype but only about the intermediate boards that it was tested on. However, both the firmware andthe hardware schematics of the tested prototypes were made available as open-source [11].

Considering all the discussed candidates and bearing in mind the selection criteria defined, it canbe stated that the Ledger Nano Hardware Wallet is not an option for the base wallet as it is not possibleto modify its source-code. The Trezor and KeepKey Hardware Wallets had their code developed andoptimized for the platform that they are implemented on and as such using a different platform wouldrequire a huge effort to guarantee the same performance, functionality, and security. On the other hand,BitSafe’s prototype was specially developed to be platform-independent. Furthermore, it also providesgood security features and it is fully open-source. In this way, as the BitSafe’s development prototype isconsidered the most promising base wallet it is the one that is chosen to play that role. In the Table 3.2more details about some of its main characteristics can be found.

Table 3.2: BitSafe’s development prototype main characteristics [87].

Classification - Cold wallet;- Hardware wallet.

Functions- Parse transactions, prompt the user and sign transactions;- Store all the private keys;- Through a basic application it can scan the Bitcoin blockchain and generate transactions [94].

Features

- Possibility of having multiple and independent wallets in one device;- Possibility of having hidden wallets which existence cannot be confirmed without the correct encryp-tion key;- Secure formatting doing a multipass, low-level overwrite with random data;- Deterministic wallet. All addresses are generated from a random seed, so that once a backup isdone, no further backups are necessary;- Wallet backups can be encrypted using AES-XEX-128;- All potentially dangerous operations require user confirmation;- When signing a transaction, all output addresses and amounts are displayed, as well as the trans-action fee.

Project

- Open source [11] (License: BSD 2-clause [92]);- Platform independent implementation;- Tested on Microship PIC 32 bit MCU [95];- Tested on Microcontroller NXP LPC11U24 [96];- Tested on AVR board with ATmega328 chip [97].

Versions

Five versions of this wallet were developed:- Version 1: First prototype [85];- Version 2: Improved prototype [86];- Version 3: Development prototype [87];- Version 4: BitSafe first generation [98];- Version 5: BitSafe second generation [71].

OriginalCreators

- Firmware: Chris Chua, known as "someone42" in bitcointalk.org;- Hardware: "allten" as it is known in bitcointalk.org

Requirements - Required RAM: 8 kilobytes;- Required non-volatile memory per wallet: 160 bytes.

27

Page 44: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

3.2 Base Wallet Description

In this section the contents of the base wallet chosen in section 3.1 will be described, as a way toidentify which are the major modules that it is made of and how its storage is partitioned. Through thedivision of base wallet into blocks it becomes easier to perform a more detailed analysis of the same.Therefore, it also allows to identify critical points where the security can be improved with more ease. Thestorage is actually one of the most sensitive components of any security application, as it usually storesconfidential and private information, which if compromised could lead to dire consequences. Thus, anunderstanding of the base wallet storage constitution is essential to guarantee that the data stored, suchas private keys, are well protected. Moreover, this categorization is used to support the design processof selecting which sections should be switched to a more secure environment.

As the only information that was available about the base wallet was related with the communicationprotocol between the hardware device and the host, and the features that it provided, it was needed toexamine all the source-code [11] to find out its main modules. After a complete and careful analysis,the following components were identified: Storage, Wallet Functions, Transaction Functions, Pseudo-Random Number Generation Functions, and Cryptographic Operations. Each one of these componentswill be described in more detail in the following paragraphs.

Storage: The storage is divided in two partitions as it is depicted in Figure 3.1, one is called GlobalPartition, where the general information about the Hardware Wallet is stored, and the other one is calledAccounts Partition, where all the created wallets are stored. In turn, each wallet is divided into twosections, one with sensitive data that is encrypted using AES in Xor-Encrypt-Xor mode with 128 bits(AES-XEX-128) [99], with keys derived from a password defined by the user along with a cryptographicsalt, while the other section is unencrypted and contains general content about the wallet. However, itis important to notice that, if the user chooses to not use a password the sensitive data is stored in anunencrypted form.

Storage

Entropy Pool

Entropy Pool Checksum

Device UUID

Wallets

-

-

-

GlobalPartition

Accounts Paritition

Encrypted

Unencrypted

Wallet Constituition0

64

96

112

128

144

512

1536

Version

Reserved

Name

UUID

Number of Addresses

Padding

Reserved

Seed

Checksum

Figure 3.1: On the left it is displayed how the Storage is partitioned, and on the right it is shown theinformation stored in each wallet. The represented memory is byte addressable.

The Global Partition includes an Entropy Pool, which is where some random bits are stored and usedas a source to produce cryptographically secure random numbers. To avoid any faults with the entropypool, it also stores its checksum (Entropy Pool Checksum). The last thing that it includes is a DeviceUUID that it is attributed to each Hardware Wallet for identification purposes. Furthermore, in Figure 3.1the memory addresses that were originally defined by the BitSafe’s firmware author are also presented.There are three regions of memory that remain empty: i) “the reason for not using 0 - 64 is that old

28

Page 45: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

revisions of some Atmel atmega328p chips (that chip was the first target of BitSafe) had reliability issueswith storage in that area”1; ii) “the 112 - 128 hole is so that there is room for a bigger pool checksum, ifthat becomes necessary ”1; iii) “The large hole from 144 - 512 was reserved for future expansion of theentropy pool to make it not overwrite the region 64 - 112 so much”1.

Regarding the Accounts Partition, it is composed of all the wallets that the user has “installed”.Each Wallet has critical data that is stored in an encrypted form2, like the Seed from where the Bitcoinaddresses are generated, or the Padding which corresponds essentially to random bytes that are usedto discourage known-plaintext attacks. The Number of Addresses is an encrypted variable that indicatesthe number of Bitcoin addresses that were already generated from the Seed, and as such, it is used toknow the number of iterations that are needed for the next time a new address is requested. Anotherencrypted field of great importance is the Checksum, which is the resulting SHA with 256 bits hash ofwallet’s contents, and allows that any unauthorized modifications to the remaining fields to be easilydetected. For example, when the user changes from the current wallet to another that it is stored onthe device, it is performed the SHA with 256 bits upon the contents of the loaded wallet, and if theobtained hash differs from the one that is stored in the Checksum field, then it is known that the walletwas tampered with. This verification takes also into account unwanted modifications to the Checksum,because if it is modified it will still not match with the obtained hash. Taking into consideration possiblefuture features, it is also included an encrypted Reserved field. There are a couple of other variablesthat are stored in an unencrypted form, such as the Version field, which can have one of three possiblevalues: “encrypted”, “unencrypted” or “nothing there”. If the user defined a password for the wallet, itmeans that the sensitive information is “encrypted”, otherwise if the user opted to not use a passwordthe sensitive information remains “unencrypted”. The default value for the Version field is “nothing there”,which can have two meanings: that actually there is nothing there, or the user defined a password butchose to “hide” it by setting the field to its default value, creating, in this way, a plausible deniability aboutthe wallet’s existence. As mentioned before, along with the password it is used a cryptographic salt togenerate the keys used in the encryption/decryption process, that salt is the Wallet ’s UUID unencryptedfield, which is also used as a way for the host to identify the Wallet. The two remaining unencrypted fieldsare the Reserved field and Name field, the former is not actually used and is reserved for a possiblefuture feature, while the latter is purely used with an informative purpose, which makes it not essentialfor the operation of the wallet.

Wallet Functions: It includes a set of functions that are used to operate upon the existent wallets,such as: creating, initializing, reading, writing, updating, and deleting wallet records. It also enclosesfunctions to manage the Storage, from the ones that are used to set the encryption key of a specificwallet, to the ones used to sanitize each partition. Moreover, it includes the wrapper functions used tocreate new Bitcoin addresses. In Table 3.3 the main functions of this module are specified, and a briefdescription of the same is also given.

Transaction Functions: All the needed functions to parse the Bitcoin transactions received from thehost are enclosed in this section. It also includes the wrapper functions that are used to sign eachtransaction and to encapsulate it into a format that is compatible with the Bitcoin protocol. In Table 3.4the main functions of this module are presented along with a brief description of each one of them.

Pseudo-Random Number Generation Functions: This module comprises all the functions that areresponsible for the generation of random and pseudo-random numbers. These numbers are used by

1This information was kindly provided by Mr. Chris Chua, the original author of BitSafe’s firmware, through e-mail.2As mentioned, if the user chooses to not use a password, this data remains unencrypted.

29

Page 46: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

other functions for various purposes, for example: to create the PINs that are used to confirm certainoperations, or to help generate Bitcoin addresses. The main functions of this module, as well as a briefdescription of the same are presented in the Table 3.5. The function generateDeterministic256(), is usedto generate new Bitcoin addresses, which is a function that is often used. As it was mentioned before,the wallet stores the seed and the number of addresses already generated, but not the actual addresses.This means that it is not possible to use the previous generated address to deterministically generatethe new one. Instead, it is used an iterative and deterministic process where it is used the seed as thesource and the number of addresses already created as the number of iterations to be performed. “Theadvantage of not storing addresses is that very little non-volatile storage space is needed per wallet”[11]. However, it also makes the process slower as it has to generate each one of the addresses,especially due the multiplication operation that is used in the ECDSA algorithm when generating themaster public key [11]. According to the BIP 0032, it is on the master public key that it is applied thedeterministic algorithm to generate the new Bitcoin addresses. The master public key is stored in abuffer, since it is often used, and this buffer optimizes its access time, as one does not have to accessnon-volatile memory every time.

Cryptographic Operations: The cryptographic functions encompass all the operations that are re-quired for the correct operation of the other functions. There is the SHA with 256 bits which is used, forexample, when parsing transactions. The AES, which was already mentioned in the Storage, is used toencrypt and decrypt certain elements of a wallet. The key that is used for that process is generated bythe Password-Based Key Derivation Function 2 (PBKDF2). The RIPEMD with 160 bit it is used to createBitcoin addresses, as described in subsection 2.2.2. The HMAC - SHA with 512 bits is used in theprocess of generating pseudo-random deterministic numbers, which is suitable for generating Bitcoinaddresses from a seed. HMAC - SHA with 256 bits and HMAC - Deterministic Random Bit Generator(DRBG) are auxiliary functions for implementing ECDSA, which is used to create Bitcoin addresses andsign transactions, as it was described in subsection 2.2.3.

AESSHA-256 RIPEMD-160

PBKDF2

Wallet Functions

Transaction Functions

(Pseudo-)Random Number Generation

Functions

Cryptographic Operations

General Wallet Functions

Storage

Write Cache

Wallet Functions

Transaction Functions

(Pseudo-)Random Number Generation

Functions

Wallet Storage

Cryptographic Operations

General Wallet Functions

Storage

Wallet Storage

a) b)

HMAC-SHA-512SHA-512

HMAC-DRBG

HMAC-SHA-256 ECDSA

AESSHA-256 RIPEMD-160

PBKDF2

HMAC-SHA-512

HMAC-DRBG

HMAC-SHA-256 ECDSA

Figure 3.2: The three main modules of the BitSafe wallet.

In Figure 3.2 the aforementioned components are depicted and categorized in three main modules:i) Wallet Storage, ii) General Wallet Functions, and iii) Cryptographic Operations.

30

Page 47: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

Table 3.3: Brief description of the main Wallet Functions [11].

Function Brief Description

calculateWalletChecksum() Calculates the checksum (SHA-256 hash) of the current wallet’s contents.

readWalletRecord() Loads the contents of a specified wallet from non-volatile memory.

writeCurrentWalletRecord() Stores the contents of the current loaded wallet into the non-volatile memory.

deriveAndSetEncryptionKey() Using the specified password and UUID, derives an encryption key and starts using it.

initWallet() Initializes a wallet (loads it if it’s there).

uninitWallet() Unloads wallet.

updateWalletVersion() Computes the current wallet version.

deleteWallet() Deletes a wallet from the non-volatile storage.

newWallet() Creates a brand new wallet that has an unique and unpredictable seed.

backupWallet() Starts a wallet backup of the currently loaded wallet.

makeNewAddress() Generates a new address using the deterministic private key generator.

getNumAddresses() Gets the number of addresses already created by the wallet.

getNumberOfWallets() Fetches the number of wallets that can fit into the non-volatile storage.

getMasterPublicKey() Gets the master public key of the currently loaded wallet.

getPrivateKey() Given an address handle, generates the associated private key.

getAddressAndPublicKey() Given an address handle, generates the associated address and public key.

changeEncryptionKey() Changes the encryption key of a wallet.

changeWalletName() Changes the name of the currently loaded wallet.

getWalletInfo() Gets the Version, Name and UUID of the wallet.

sanitiseNonVolatileStorage() Sanitize (clear) a selected area of non-volatile storage.

sanitisePartition() Sanitize (clear) the entire contents of a partition.

sanitiseEverything() Sanitize (clear) all partitions.

Table 3.4: Brief description of the main Transaction Functions [11].

Function Brief Description

getTransactionBytes() Gets transaction data by reading from the stream device.

isEndOfTransactionData() Checks whether the transaction parser is at the end of the transaction data.

getVarInt() Parses a variable-sized integer within a transaction, which is commonly used to representcounts or sizes in Bitcoin transactions.

parseTransaction() Parses a Bitcoin transaction.

parseTransactionInternal() Helper function of the parseTransaction() function.

encapsulateSignature() Encapsulates an ECDSA signature into a format compatible with the Bitcoin protocol.

signTransaction() Signs a transaction.

31

Page 48: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

Table 3.5: Brief description of the main Pseudo-Random Number Generation Functions [11].

Function Brief Description

setParentPublicKeyFromPrivateKey() Sets the master public key for the deterministic key generator.

clearParentPublicKeyCache() Clears the master key buffer.

calculateEntropyPoolChecksum() Calculates the entropy pool checksum of an entropy pool state.

setEntropyPool() Sets (overwrites) the persistent entropy pool.

getEntropyPool() Obtains the contents of the persistent entropy pool.

initialiseEntropyPool() Initializes the persistent entropy pool to a specified state.

getRandom256Internal() Accumulates entropy using a source of randomness, and the state of a persistent pool tothe source if wanted, in which case the pool is updated after use.

getRandom256() Version of getRandom256Internal() which uses the persistent entropy pool from non-volatile memory.

getRandom256TemporaryPool() Version of getRandom256Internal() which uses a temporary persistent entropy pool.

generateInsecureOTP() Generates an insecure one-time password.

generateDeterministic256() Uses cryptographic primitives to deterministically generate a new 256 bit number.

Table 3.6: Brief description of the platform dependent functions [11].

Function Brief Description

getString() Obtains one character from one of the predefined strings.

getStringLength() Gets the length of one of the predefined strings.

streamGetOneByte() Grabs one byte from the communication stream.

streamPutOneByte() Sends one byte to the communication stream.

newOutputSeen() Notifies the user interface of a new Bitcoin amount/address pair.

setTransactionFee() Notifies the user interface that the transaction parser has been informed of the transactionfee.

clearOutputsSeen() Notifies the user interface that the list of Bitcoin amount/address pairs should be cleared.

displayAddress() Informs the user that a Bitcoin address has been generated.

userDenied() Asks the user if he allows the execution of the displayed action.

displayOTP() Displays a short (maximum 8 characters) one-time password (PIN).

clearOTP() Clears the OTP (one-time password) shown by displayOTP() from the display.

hardwareRandom32Bytes() Fills a buffer with 32 random bytes from a hardware random number generator.

nonVolatileGetSize() Gets the size of a partition.

nonVolatileWrite() Writes to non-volatile storage.

nonVolatileRead() Reads from non-volatile storage.

nonVolatileFlush() Ensures that all buffered writes are committed to the non-volatile storage.

sanitiseRam() Overwrites anything in RAM which could contain sensitive data.

fatalError() This is called whenever something unexpected occurs.

writeBackupSeed() Writes the backup seed to some output device.

getPBKDF2Iterations() Defines the number of iterations to use on the PBKDF2 algorithm.

32

Page 49: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

As previously mentioned, the source-code of the base wallet is platform-independent. However,when porting it to another platform there are a few functions that need to be modified, namely the onesthat interact directly with the platform’s hardware and peripherals. The functions related with getting theuser’s confirmation, or displaying information into the device’s screen need to be adapted to the targethardware. The same rationale applies to the the functions that read and write directly into the storage.These functions, as well as a brief description of them are listed, in the Table 3.6.

Lastly in the Table 3.7, the available packets for the communication between BitSafe and the hostdevice are presented. These packets translate, in a certain way, the functions that are provided by thewallet for the user.

Table 3.7: Available packets for the communication between BitSafe and the host [11].Packet Function

PACKET_TYPE_INITIALIZE Reset the state of the hardware wallet and report its features.

PACKET_TYPE_PING Ping request.

PACKET_TYPE_DELETE_WALLET Delete an existing wallet.

PACKET_TYPE_NEW_WALLET Create a new wallet.

PACKET_TYPE_NEW_ADDRESS Create a new Bitcoin address.

PACKET_TYPE_GET_NUM_ADDRESSES Get the number of Bitcoin addresses already created.

PACKET_TYPE_GET_ADDRESS_PUBKEY Get the address and the public key corresponding to an specificaddress.

PACKET_TYPE_SIGN_TRANSACTION Sign a transaction.

PACKET_TYPE_LOAD_WALLET Load a wallet.

PACKET_TYPE_FORMAT Format the storage.

PACKET_TYPE_CHANGE_KEY Change a wallet’s encryption key.

PACKET_TYPE_CHANGE_NAME Change a wallet’s name.

PACKET_TYPE_LIST_WALLETS List the available wallets.

PACKET_TYPE_BACKUP_WALLET Backup a wallet.

PACKET_TYPE_RESTORE_WALLET Restore a wallet.

PACKET_TYPE_GET_DEVICE_UUID Get the device UUID.

PACKET_TYPE_GET_ENTROPY Get an arbitrary number of bytes of entropy.

PACKET_TYPE_GET_MASTER_KEYGet the master public key and chain code, which consists in thelast 32 bytes of the Seed.

3.3 Proposed Improvements

In this section, a set of modifications to the base wallet are proposed, in order to improve its functionalityand security, through the use of the TrustZone features, with the aim of creating a secure and reliableTrustZone-backed Bitcoin wallet. To achieve this, and according to the description performed in sec-tion 3.2, the base wallet’s modules as well as its functions will analyzed, to decide which are the mostcritical parts that should be implemented in a more secure environment. Herein, it is assumed that theunderlying TrustZone-enabled device implements GlobalPartform’s APIs, which guarantee the portabilityof the proposed implementation, and the scenario explained in subsection 2.1.1 is applicable, where itwas mentioned that it should have a Trusted OS, in order to create a more powerful system that boosts

33

Page 50: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

TrustZone features.Regarding the Storage component, the base wallet provided the minimum security requirements. It

stores all the critical data in an encrypted form, while the more general information remains unencrypted.However, as mentioned before, if the user chooses not to use a password, the critical data does not getencrypted, which means that the Seed, Number of Addresses already generated, Padding, Checksumof the wallet, and the Reserved field become completely vulnerable, creating the ideal scenario for anattacker. If the BitSafe device gets stolen, the attacker can use it without any restrictions as the data isno longer protected by a password. Moreover, even if the device only stores one wallet whose addressesdoes not have any funds associated, the attacker can still use the Seed and the Number of Addressesalready generated to create all the possible Bitcoin addresses that will ever be used by the wallet. Thatinformation can be valuable if the user continues to use the same wallet3, in which case he can steal anybitcoins that the user will receive in any one of those addresses. This situation can also be replicated inthe case where the BitSafe device is not stolen, but the attacker still has access to Seed.

The other content that is not encrypted can also be tampered with in order to benefit an attacker.For example, if an attacker has the possibility of reading and writing into the BitSafe’s storage, he caneasily modify the content of the Entropy Pool and then calculate its new checksum, which he woulduse to replace the existent one in the Entropy Pool Checksum field. If this happened, the EntropyPool would become compromised, and consequently the random numbers that are generated by usingits information would also be compromised. Additionally, if the attacker could invalidate the source ofrandomness, he would be able to predict the PINs that are used to confirm critical operations and, thus,invalidate the security measures that were in practice. In fact, that is one of the reasons why the functionresponsible for generating the PINs is called generateInsecureOTP().

Another unencrypted field that the attacker could tamper with, if he had the possibility of reading andwriting into the BitSafe’s storage, is the Version field. In the case that the user opted to use a passwordthe Version field is set to “encrypted”, however if an attacker changes it to “nothing there”, he createsa plausible deniability about the wallet existence, and as “updating the version field for a hidden walletwould reveal where it is” [11] the user is not able to change it, which means that the password cannot bechanged either. In this way, the attacker has invalidated the possibility of changing the encryption keyof the sensitive data, giving him enough time to discover the actual password defined by the user and,thus, retrieve all the critical data.

Even without the aforementioned security issues, the sensitive data is still susceptible to attacks.Usually, the users tend to choose very simple and common passwords, or they simply use the samepassword that they use for other services. In a report released in beginning of 2016 by SplashData[100], a company that provides password management applications, compiled more than two millionpasswords that were leaked during the year of 2015, and concluded that the most used passwords are“123456” and “password”, which are the same as the year of 2014. This way, the encrypted sensitivedata is vulnerable to dictionary-based attacks, where an attacker tries a large amount of the most typicalpasswords for decrypting the data, until he finds a suitable one. Once that happens, the attacker has fullaccess to the Seed and to the other fields, ending up in the same situation as the previously mentioned.

Moreover, as it is intended, in the final solution, to give the possibility of having multiple applicationsin the same device, to the presented vulnerabilities it would be added the ones associated with softwaresolutions, where the mentioned attacks can also be performed by malicious applications. It is easier toan application that runs in the same device as the BitSafe software to access and tamper with its storagethan an attacker who would need physical access.

Due to these vulnerabilities, it is proposed to add an extra layer of security and protection, whichis implemented by transferring the BitSafe’s storage into TEE, where it is marked as secure making

3Which is only possible if the user has previously saved the Seed.

34

Page 51: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

it only accessible through the Secure World. GloblalPlatform’s TEE Internal Core API specification[30], dictates that it should be possible to store general-purpose data, as well as key material, with theguarantee that the confidentiality and integrity is maintained. For that, it specifies that each operationthat acts on the storage and is not successful, does not produce any change, and it also mandates thefollowing requirements for the secure storage4:

1. “The Trusted Storage may be backed by non-secure resources as long as suitable cryptographicprotection is applied, which MUST be as strong as the means used to protect the TEE code anddata itself ” [30]. In some implementations of the TEE, the secure storage space is located in theNormal World’s file system, where the data is stored encrypted with a key that is located in asecure region of the device’s memory, which is only accessible to the Secure World. This meansthat whenever a TA wants to update some stored data, it first needs to fetch into the Secure Worldthe disk sector that contains the correspondent data from the Normal World’s file system. Oncethe data is in a secure region of the Secure World it gets decrypted, and then is sent to the TA,which updates it with the new data and sends it back to the secure region where it came from.Finally, the disk sector is encrypted again and transfered to the secure storage space;

2. “The Trusted Storage MUST be bound to a particular device, which means that it MUST be ac-cessible or modifiable only by authorized TAs running in the same TEE and on the same deviceas when the data was created” [30]. This requirement gives the guarantee that even if the securespace data and the TA are copied to a different device, it is still not possible to access the data, asit is encrypted with a key that is bound to the device where the data was originally created.

3. “Ability to hide sensitive key material from the TA itself ” [30]. This implies that the process ofencryption and decryption of the secure storage space data should not be performed with keysthat are fully accessible by the TAs. In this way, one TA cannot interfere with the data created byanother TA;

4. “Each TA has access to its own storage space that is shared among all the instances of that TA butseparated from the other TAs” [30]. This requirement along with the previous one, allows to havean isolation between different TAs, which is ideal for the wallet proposed herein as it is intended tohave different TAs with different purposes securely running on the same device;

5. “The Trusted Storage must provide a minimum level of protection against rollback attacks. It isaccepted that the actually physical storage may be in an unsecure areas and so is vulnerableto actions from outside of the TEE” [30]. This means that the TEE provides a certain level ofprotection for when one tries to replace the secure storage with outdated data.

The implementation of all these requirements can mitigate the vulnerabilities before mentioned forthe BitSafe’s storage. A user not using a password is no longer considered a threat as the data is stillstored in an encrypted form by the TEE in the secure storage space with a key that is securely generatedand stored. This also covers the cases where the user chooses a weak password, since the additionalencryption makes dictionary-attacks impractical, namely for the situations where an attacker exploitsavailable bugs on the Normal World, or when he tries to intercept the communication made betweenthe two worlds. The fields that were stored unencrypted, such as the Version field, Entropy Pool, andEntropy Pool Checksum, are now encrypted and, in fact, the whole BitSafe’s storage is encrypted. Thisremoves the possibility of easily tampering with those fields and, thus, it becomes much more difficultto compromise and avoid the security measures that were implemented. The malicious applications are

4The secure storage in the GlobalPlatform’s APIs is referred to as Trusted Storage.

35

Page 52: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

also noneffective when it is intended to interfere with the data that is stored or that is being processed,because even if they are malicious TAs installed to break the conditional access to the memory regionwhere the wallet storage is located, it is still not possible to decrypt the data as the key is hidden from theTAs itself. Moreover, as each TA has its own individual and secure memory space, malicious applicationscannot break into other TA memory spaces with the intent of stealing the data while it is being processed,or even try to tamper with execution variables, as TrustZone does not allow it.

Nevertheless, it is worth to notice that the process of reading and writing into the secure storagespace has now an associated overhead, due the encryption and decryption operations. In this way, asecure write-cache is also proposed, where intermediate results are stored, and later flushed into thesecure storage, to speed-up the write and read operations. The write-cache consists of a buffer with thesize of a disk sector located in secure memory. Whenever there is data to be written, it is checked if thecorrespondent disk sector is already available in the cache. If it is not, the disk sector is loaded into thecache and the previous content is flushed. For the reading process, if the data that is requested is onthe disk sector that is loaded on the cache, then it is read from there, and otherwise, the data is readdirectly from the secure storage.

At this point, it is possible to deduce that the secure execution of the Cryptographic Operationsis crucial, as they are the most used operations by the remaining components. If one of the crypto-graphic operations became compromised, every single wallet stored in the device would also be com-promised. For example, these functions are used to encrypt information, generate cryptographic keys,create checksums, and generate Bitcoin addresses, which are orthogonal functions to every wallet. TheGlobalPlatform’s TEE Internal Core API specification [30] has a section where it specifies a Crypto-graphic Operations API, which provides almost every one of the used operations. The SHA with 256bits and with 512 bits, AES, HMAC - SHA with 256 bits and with 512 bits, and ECDSA are all men-tioned. However, the last one, ECDSA, is only optionally provided. Thus, it is proposed not to usethe API for that function, and instead implement it manually, as a way to maintain the portability andplatform-independence of the final solution. In addition, the RIPEMD with 160 bits, HMAC - DRBG, andPBKDF2 should also be implemented manually as they are not provided by the API. For the remainingcryptographic operations, it is proposed to use the provided Cryptographic Operations API as it offers asecure and trustworthy execution. The OEMs can improve even further the security of those functionsby optimizing the same API to the marketed devices.

For the General Wallet Functions, it is proposed to fully transfer to the Secure World only the mostcritical functions. Additionally, for the ones that process and/or produce sensitive data, it is also proposedto remove the possibility of invoking them outside the Secure World. However, it is important to noticethat, for certain functions, it is not possible to remove its invocation from the Normal World, becauseeither they provide features that are specified by one of the packets described in the Table 2.1, orthey are invoked by other functions that are not proposed to be transfered to the Secure World. For thefunctions that have only part of their code used to process/create sensitive data, it is proposed to transferto the Secure World only those sections. For the remaining functions, it is proposed to maintain theirimplementation in the Normal World, because either they are not critical, or they use functions that arealready fully or partially proposed to be implemented in the Secure World. In this way, it is expected tonot increase too much the size of the TA that will provide the General Wallet Functions. This is becauseit is important the amount of code that runs on the Secure World to be minimal, so that it can be easilyreviewed, analyzed, and the quantity of bugs be minimized.

Regarding the Wallet functions, it is proposed to transfer the current wallet cache to the Secure Worldto avoid any tampering with the same, and maintain the confidentiality obtained by transferring storageto the Secure World. Based on the descriptions provided in Table 3.3, the following propositions are alsomade:

36

Page 53: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

• calculateWalletChecksum(): It is proposed to fully transfer this function to the Secure World andremove the possibility of invoking it from the Normal World. The reason for that is that to calculatethe checksum, all of the wallet’s content has to be processed, and if this content is processed inthe Normal World some of the aforementioned vulnerabilities would become exploitable;

• readWalletRecord(): It is proposed to fully transfer this function to the Secure World and removethe possibility of invoking it from the Normal World. This function retrieves a wallet from the Bit-Safe’s storage that is located on the secure storage space. If this function were available to theNormal World, it would mean that the some of previously described vulnerabilities were present;

• writeCurrentWalletRecord(): For a similar reason to why the readWalletRecord() was convertedto the secure world, it is proposed to fully transfer this function to the Secure World and removethe possibility of invoking it from the Normal World;

• deriveAndSetEncryptionKey(): It is proposed to fully transfer this function to the Secure Worldand remove the possibility of invoking it from the Normal World. The main reason is that thisfunction processes the user’s password to generate an encryption key. Moreover, it also startsusing the encryption key, and by removing this function from the Normal World it is removed thepossibility of replacing the key by a malicious one;

• initWallet(): It is proposed to only transfer the essential section of this function to the SecureWorld. To initialize a wallet functions like calculateWalletChecksum(), readWalletRecord(), andderiveAndSetEncryptionKey() are invoked, which are fully implemented in the Secure World andwithout the possibility of invoking them through the Normal World. This means that the section ofthe code that uses this operations should also be implemented in the Secure World;

• uninitWallet(): It is proposed to fully transfer this function to the Secure World. Since this functionresets some of the execution variables that are used, as well as the master key buffer, which areoperations fully implemented in the Secure World, so should be this function;

• updateWalletVersion(): It is proposed to fully transfer this function to the Secure World and re-move the possibility of invoking it from the Normal World. This modification removes the possibilityof unwanted modifications of the Version field, thus preventing previously described vulnerabilities;

• newWallet(): It is proposed to only transfer the essential section of this function to the SecureWorld. The section that should be transfered is related with the functions that it invokes and areproposed to be fully implemented on the Secure World, which make also the most critical sectionof this function;

• backupWallet(): It is proposed to only transfer the essential section of this function to the SecureWorld. In this function it is presented the Seed to the user, which means that it needs to be fetchedfrom the BitSafe’s storage. To avoid any tampering with that process it is proposed to convert it tothe Secure World;

• getNumAddresses(): It is proposed to fully transfer this function to the Secure World. As thename indicates, this function accesses the Number of Addresses field of a wallet, and as thesecure space storage is only accessible through the Secure World, it is proposed to implementthis function there also;

• makeNewAddress(): It is proposed to fully transfer this function to the Secure World. As it wasalready described, the process of generating a new address uses the Seed and Number of Ad-dresses fields, which are only accessible in the Secure World. As such, and to avoid any tampering

37

Page 54: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

with the process of generating new addresses, it is proposed to transfer this function to the SecureWorld;

• getMasterPublicKey(): It is proposed to fully transfer this function to the Secure World, since itneeds to access the Seed which should not be exposed to the Normal World;

• getPrivateKey(): It is proposed to fully transfer this function to the Secure World and remove thepossibility of invoking it from the Normal World. This is one of the most critical functions as it allowsto get the private keys associated with every Bitcoin Addresses ever generated, thus it should onlybe executed inside the Secure World and without the option of invoking it in the Normal World. Inthis way, the private keys would never leave the TEE, strengthening the security features of theproposed wallet;

• getAddressAndPublicKey(): It is proposed to fully transfer this function to the Secure World. Thepublic keys are generated from the correspondent private keys, which means that this functionneeds to access the private keys stored in BitSafe’s storage, and as it is proposed to restrain theaccess to those to the Secure World, this function should also be implemented there;

• changeEncryptionKey(): It is proposed to fully transfer this function to the Secure World. Thisfunction uses the deriveAndSetEncryptionKey(), updateWalletVersion(), calculateWalletChecksum(),and writeCurrentWalletRecord() functions, which are all functions that were proposed to be trans-fered to the Secure World and without the possibility to invoke them through the Normal World.Thus, this function should also be transfered to the Secure World. However, it should also be pos-sible to invoke it in the Normal World as it is one of the functions that is provided by the packetspresented in the Table 3.7;

• changeWalletName(): It is proposed to fully transfer this function to the Secure World. Thisfunction uses the calculateWalletChecksum() and writeCurrentWalletRecord() functions to changethe wallet name, which are proposed to be only executed in the Secure World and without thepossibility of invoking them in the Normal World, which means that this function should also beimplemented in the Secure World;

• getWalletInfo(): It is proposed to only transfer the essential section of this function to the SecureWorld corresponding to the code associated with retrieving the wallet information as it is onlyaccessible in the Secure World.

For the Transaction Functions, and based on the description provided in Table 3.4, the followingproposals are made:

• signTransaction(): It is proposed to fully transfer this function to the Secure World. This is alsoone of the most critical functions, as it is used to sign a transaction using the ECDSA algorithmwith the private key, which is only accessible through the Secure World, and to avoid transferringthe private key back to the Normal World at the risk of exposing it, it is proposed to transfer thisfunction to the Secure World.

For the last component, Pseudo-Random Number Generation Functions, the first proposition is totransfer the master public key buffer to the secure world as most of the functions that will act on it, willalso be transfered to the Secure World. More specifically, and based on the description provided in theTable 3.5, the following propositions are made:

• setParentPublicKeyFromPrivateKey(): It is proposed to fully transfer this function to the SecureWorld and remove the possibility of invoking it from the Normal World. The reason for this proposal

38

Page 55: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

has to do with the fact that the private key is processed. Moreover, this function is only neededinside the Secure World as it is only invoked by functions that were proposed to be transfered tothe Secure World, thus there is no need of having the possibility of invoking it in the Normal World;

• clearParentPublicKeyCache(): It is proposed to fully transfer this function to the Secure Worldand remove the possibility of invoking it from the Normal World, since it sanitizes the master keybuffer. As the master key buffer is located in the Secure World there is no need of this function inthe Normal World;

• calculateEntropyPoolChecksum(): It is proposed to fully transfer this function to the SecureWorld and remove the possibility of invoking it from the Normal World. The Entropy Pool andthe Entropy Pool Checksum are only accessible through the Secure World, which means that thisfunction should also be transfered there;

• setEntropyPool(): It is proposed to fully transfer this function to the Secure World. This functionuses the calculateEntropyPoolChecksum() function which is proposed to be only accessible in theSecure World, thus this function should also be executed there. In this way, it is also avoided anypossible tampering during the processing of the entropy pool content;

• getEntropyPool(): It is proposed to fully transfer this function to the Secure World. This functionhas the same requirements as the setEntropyPool() function;

• generateDeterministic256(): It is proposed to fully transfer this function to the Secure World.This function is a critical one, and it uses the setParentPublicKeyFromPrivateKey() function andaccesses the Seed field, both of which are only available in the Secure World. For these reasonsit is proposed to transfer this function to the Secure World;

The final propositions are related with the platform dependent functions, GlobalPlatform’s TrustedUser Interface API was used whenever it is possible, to interact with the platform’s peripherals. Never-theless, based on the description provided in Table 3.6, the following propositions are made:

• hardwareRandom32Bytes(): It is proposed to fully transfer this function to the Secure World. Asthis function is used to get cryptographic strong random numbers it should be guaranteed that itis not tampered with. The GlobalPlatform’s TEE Internal Core API provides a function to generatesecure random numbers. In this way, it is proposed to use that function implemented in the SecureWorld;

• nonVolatileWrite(): It is proposed to fully transfer this function to the Secure World. This is thefunction that is used to write into the secure storage space, as such it should be implemented inthe Secure World;

• nonVolatileRead(): It is proposed to fully transfer this function to the Secure World. The samereasoning used in nonVolatileWrite() function is applied here;

• nonVolatileFlush(): It is proposed to fully transfer this function to the Secure World. The samereasoning used in nonVolatileWrite() function applies here;

• getPBKDF2Iterations(): It is proposed to fully transfer this function to the Secure World. As it wasmentioned, the PBKDF2 was proposed to be transfered to the Secure World, thus, this functionsshould also be implemented in the Secure World.

39

Page 56: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

AESSHA-256 RIPEMD-160

PBKDF2

Wallet Functions

Transaction Functions

(Pseudo-)Random Number Generation

Functions

Cryptographic Operations

General Wallet Functions

Storage

Write Cache

Wallet Functions

Transaction Functions

(Pseudo-)Random Number Generation

Functions

Wallet Storage

Cryptographic Operations

General Wallet Functions

Storage

Wallet Storage

a) b)

HMAC-SHA-512SHA-512

HMAC-DRBG

HMAC-SHA-256 ECDSA

AESSHA-256 RIPEMD-160

PBKDF2

HMAC-SHA-512

HMAC-DRBG

HMAC-SHA-256 ECDSA

Figure 3.3: BitSafe’s main modules. a) Initial configuration. b) Final configuration. The dotted boxesare fully implemented in the Normal World, the dashed boxes are partially implemented in the SecureWorld and the full boxes are completely implemented in the Secure World. Some of the CryptographicOperations are only used to implement the functions of the boxes they are contained.

In Figure 3.3.a) Figure 3.2 is replicated, and in Figure 3.3.b) the configuration of the base wallet withthe proposed improvements that will constitute the final TrustZone-backed Bitcoin Wallet is presented.

The proposed changes ensure that the handled sensitive data and code cannot be tampered with byany other application in the same device allowing multiple security-sensitive applications to run simul-taneously. The proposed system is thus much more flexible than most hardware-wallets, since it canbe used simultaneously for other applications, such as those used for home-banking, user authentica-tion and trusted processing. Moreover, the use of TrustZone which provides integrity checking allowsto detect unauthorized changes to the BitSafe’s source-code. In this way, the trust upon the wallet isincreased along with the functionality and security.

3.4 Summary

This chapter started with the discussion of which of the available types of Bitcoin wallets would benefitmore when integrated into a TrustZone-enabled platform. It was concluded that Hardware Wallets werethe ones more prone to increase their security and functionality. Among the different wallets availablefor the chosen type, the most popular ones were considered for the base wallet. For those, threeselection criteria were defined: i) the possibility of modifying the firmware; ii) the device’s processor,and last but not least, iii) the level of the source-code dependency on the platform where the wallet wasimplemented. Each candidate was analyzed according to the selection criteria, and their strengths andweaknesses. The BitSafe’s development prototype was considered the most fitted and, as such it wasthe one chosen for the base wallet.

Then, a more detailed analysis was performed regarding the base wallet, where it was describedeach one of the components that it is made of: Storage, Wallet Functions, Transaction Functions,Pseudo-Random Number Generation Functions, and Cryptographic operations.

Lastly, several significant improvements for the base wallet that took advantage of the TrustZonefeatures were proposed, in order to create a TrustZone-backed Bitcoin Wallet with increased securityand functionality. It was proposed to make use of the trusted storage, and of the available APIs to

40

Page 57: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

perform cryptographic operations. It was also proposed to execute the most critical operations onlyin the Secure World by implementing them in TAs. For example, regarding the Wallet Functions, thefunctions related with getting and setting the cryptographic keys should only be handled inside theSecure World and without the possibility of anyone invoking them in the Normal World. Furthermore,the processes of creating new wallets, initializing them, as well as backing them up should have theircritical sections restricted to the Secure World. For the Transaction Functions, the most important ones,such as signing, should also be converted to the Secure World as they have the most impact in thewhole wallet. For the Pseudo-Random Number Generation Functions, the ones that process the dataof the Entropy Pool should be safely executed in the Secure World to avoid tampering it. Finally, theCryptographic Operations should exploit the provided APIs to obtain cryptographically strong randomnumbers, which is an important requirement in several cryptographic implementations. Moreover theusage of the APIs, enable the circuit vendor to implement their versions of each cryptographic operationin a way that minimizes the possibility of side-channel attacks in their platform, further improving security.

41

Page 58: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

42

Page 59: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

CHAPTER 4

IMPLEMENTATION DETAILS AND SYSTEM

ASSESSMENT

Contents

4.1 TrustZone-enabled Platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

4.2 Software Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

4.3 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

4.3.1 Platform Con�guration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

4.3.2 Implementation Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

4.4 Experimental Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

4.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

43

Page 60: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

In this chapter the implementation of the propositions made in Chapter 3 is discussed, and experi-mental results are presented, which support the practical interest of the proposed TrustZone-based Bit-coin wallet. First, a platform which is suitable for the development of TrustZone-backed Bitcoin wallet willbe presented. Then, as it is intended to exploit the TrustZone technology to the most, the software stackthat will implement the Trusted OS and provide the GlobalPlatform’s APIs implementation will be chosen.The procedure followed to integrate the software stack into the chosen TrustZone-enabled platform willalso be presented. Moreover, the porting process of the base wallet, as well as the most important mod-ifications performed to implement the proposed wallet will be described. Lastly, the methodology andprocedure adopted for an experimental evaluation of the performance of the implemented TrustZone-based wallet along with an analysis of the main obtained results will be provided.

4.1 TrustZone-enabled Platform

As it was mentioned in section 3.1, the chosen base wallet is a prototype that was released a few yearsago, and it is not know exactly which hardware was used. Furthermore, as there is no informationabout the processor that was used, even if there was the possibility of obtaining it there would be noguarantee that would support TrustZone. Nevertheless, as all the code is publicly available and there isthe possibility of modifying it, since the underlying license allows it, the base wallet can be deployed ina different platform whose processor supports the TrustZone technology. Therefore, the next step is tochoose a platform for that same end.

Table 4.1: Processors with TrustZone support. [101, 102]ARM Family ARM Architecture ARM Core Announced

ARM 11 ARMv6Z ARM1176JZ(F)-S 2003

Cortex-A (32-bit)ARMv7-A

Cortex-A5 2009Cortex-A7 2011Cortex-A8 2005Cortex-A9 2007Cortex-A12 2013Cortex-A15 2010Cortex-A17 2014

ARMv8-A Cortex-A32 2016

Cortex-A (64-bit) ARMv8-A

Cortex-A35 2015Cortex-A53 2012Cortex-A57 2012Cortex-A72 2015Cortex-A73 2016

To be announced ARMv8-M To be announced 2015

In Table 4.1, ARM processors that support the TrustZone technology are listed1. The ideal processorwould be the one that has implemented the ARMv8-M architecture, as it was designed focusing onsecurity and it is the first one that is oriented to microcontrollers2 to include ARM’s TrustZone technology[103]. However, up until now, it was not released any processor that implemented such architecture.Furthermore, there are several end-consumer platforms that feature the other referred processors, but

1The last table entry is an exception, it only presents the ARM Architecture, as it is the only information that is available, butdue its relevance it was also included.

2From the seventh generation of the ARM’s architecture, ARMv7, three different architecture profiles were defined: Applicationprofile, Real-time profile, and the Microcontroller profile. Each ARM architecture and core refer to the first letter of the profile forwhich they were designed.

44

Page 61: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

most of them have restricted access or none at all to the TrustZone technology, which is imposed bythe OEMs itself due security reasons. Moreover, some of them have proprietary implementations of theTEE which makes the development process less affordable. In the other end of the spectrum, TrustZone-enabled development platforms were designed to make full use of its features, which means that theyhave not only the capability of running TAs, but also allow to install and debug them.

At the time of this writing, there are four TrustZone-enabled development board that are widely usedfor the development of TAs, namely: i) Xilinx Zynq-7000 AP SoC ZedBoard [104], ii) HiKey Board(HiSilicon Kirin 620) [105], iii) Freescale iMX53-QSB [106], and iv) ARM Juno Board [107]. The maincharacteristics of these boards are summarized in the Table 4.2, from which it is possible to observe thatall of these boards are suitable since they fulfill the minimum requisites imposed by the base wallet: theyhave more than 8 kilobytes of RAM and, at least, 160 bytes of non-volatile memory.

Table 4.2: Main characteristics of TrustZone-enabled development boards.

Development Board Processor’sArchitecture Processor RAM

MaximumFrequency Flash memory

Xilinx Zynq-7000 APSoC ZedBoard[104]

ARMv7-A Dual ARM Cortex-A9MPCore.

512 MBDDR3 667 MHz 256 Mb Quad-SPI

Flash

HiKey Board (HiSiliconKirin 620)[105]

ARMv8-A ARM Cortex-A53Octa-core.

1 GB or 2GBLPDDR3

1.2 GHz 8GB eMMC

Freescale iMX53-QSB[106] ARMv7-A ARM Cortex-A8 core. 1GB DDR3 1 GHz 4GB or 8GB NAND

Flash

ARM Juno Board[107]

ARMv8-Abig.LITTLE

- big cluster: Dual-coreCortex-A57 or Cortex-A72;- LITTLE cluster:Quad-core Cortex-A53.

8 GBDDR3L

- Cortex-A72:1.2 GHz;-Cortex-A57:1.1GHz;-Cortex-A53:850MHz

64MB NOR Flash

The main differences between the platforms that are presented in Table 4.2, besides the amountof RAM and Flash memory, resides in the processor’s architecture and on the cores that make use ofit. Both the Xilinx Zynq-7000 AP SoC ZedBoard and Freescale iMX53-QSB have processors with theARMv7-A architecture [108] but, while the former uses two Cortex-A9 cores, the latter only uses oneCortex-A8 core. In turn, the HiKey Board (HiSilicon Kirin 620) and the ARM Juno Board, have processorsthat implement the ARMv8-A architecture; in the former, eight Cortex-A53 cores are used, and in thelatter two Cortex-A57 or Cortex-A72 cores are combined with four Cortex-A53 cores in a big.LITTLE®

implementation [109]. big.Little is an ARM technology that uses two different types of processor cores:“LITTLE” cores, which are designed for maximum power efficiency, and “big” cores that are designed toprovide maximum compute performance [109]. The internal differences in the microarchitecture betweenbig and LITTLE cores allow to provide a more power-aware solution.

The ARMv8 is the most recent ARM architecture and it was the first one that supported a 64-bitinstruction set. It “broadens the ARM architecture to embrace 64-bit processing and extends virtualaddressing, building on the rich heritage of the 32-bit ARMv7 architecture upon which market leadingcores such as the Cortex-A9” [110] and Cortex-8 processors are built. In this way, the HiKey Board(HiSilicon Kirin 620) and the ARM Juno Board are preferable. However, the ARM Juno Board is anofficial ARM development board which means that it is highly supported and has a good amount ofdocumentation available [107]. Moreover, ARM created this platform with the intent of offering hardwareand software developers a chance to work on next-generation hardware with their latest designs [107].Since its hardware represents the future of consumer devices, they will ultimately be used for Bitcoin

45

Page 62: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

wallets, and thus are most relevant for this proposal. At the present moment, there are three variants ofthis board, the last version is the ARM Juno-r2 board which has an ARMv8-A big.Little architecture, witha 1.2 GHz dual-core Cortex-A72, and a 850 MHz quad-core Cortex-A53, with 8GB of DDR3L RAM [13].It also provides the possibility of using all the debug modes available for the TrustZone.

Due to all the facts mentioned, the ARM Juno-r2 Board is the most suitable platform, and as such itis the one that will be used. Nevertheless, it is important to mention that despite the chosen platform, thedevelopment process will be as general as possible, so that as the final solution is platform-independent.

4.2 Software Stack

In subsection 2.1.1, the ideal scenario for the TEE was presented. It was mentioned that it should havean Trusted OS whose implementation was in accordance with the GlobalPlatform’s APIs in order tocreate a more powerful system that makes the most of the TrustZone features.

Currently, there are multiple implementations available for the OSs that run on the Secure and Normalworlds. OP-TEE [21] provides both of them, and at the moment it is the only one that supports theARM Juno Board. Its implementation is based on a proprietary solution that was initially created byST-Ericsson® and later acquired and maintained by STMicroelectronics® [21]. In 2014, Linaro® starteda collaboration with STMicroelectronics with the aim of converting the solution into open-source [21].In 2015, the project was transferred permanently to Linaro, and since then they are responsible for itsmaintenance. Nevertheless, as project is open-source it is also supported by developers from all overthe world who make ongoing contributions.

During the development of the OP-TEE, three main goals were taken into account [14]: i) to providea secure and isolated environment for the TEE where different TAs are also isolated from each other;ii) to create an implementation with the smallest foot print as possible so it could reside in a smallamount of on-chip memory; and iii) to provide a portable solution that could be easily implementedin different architectures and hardware. To accomplish these goals the TEE is implemented accordingwith the GlobalPlatform TEE System Architecture specification [28]. For the Normal World, BusyBox isused as the operating system, since it was mainly developed to be used on embedded devices with lowcomputational power. In the Secure World, that role is fulfilled by the OP-TEE OS whose size is about244 KB. It is important to note that the code for the Trusted OS should be minimal not only to occupy thesmallest possible space in memory but, since it comprises the trust anchor, to also be easily reviewedand have the minimum attack surface.

In Figure 4.1 it is presented the software architecture of the OP-TEE. When compared with Fig-ure 2.1, it becomes possible to highlight the OP-TEE software stack. The TEE Client API is implementedby the OP-TEE Client, which provides the Client API as defined by the GlobalPlatform TEE Client APISpecification [29] for the CAs, so they can communicate with the Trusted OS whenever one wants thesecure execution of applications within the TEE. Moreover, the OP-TEE Client also has a TEE Sup-plicant which is a daemon that provides to the Trusted OS miscellaneous features, such as Storageaccess. The OP-TEE Driver is a Linux Kernel TEE driver that handles the communication betweenNormal World’s user space and the Secure World. Lastly, the Trusted OS, Secure Monitor, and theTEE Internal Core API are implemented by the OP-TEE OS, the latter having the GlobalPlatform TEEInternal Core API [30] into consideration. Unfortunately, the GlobalPlatform Trusted User Interface APISpecification [31] is not included as its implementation is not fully developed. Besides the presentedsoftware stack, OP-TEE also has available a TEE sanity test suite, which is denominated xtest [111].

46

Page 63: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

Pri

vile

ged

sp

ace

Use

r sp

ace

Pri

vile

ged

sp

ace

Use

r sp

ace

Normal OS

OP-TEE

Generic Application

Application with Secure OS support

Security Client

Wrapper APIs(Optional)

Storage OP-TEE Driver

Hardware Resources(crypto, timers, watchdog, fuses, ...)

Secure Monitor

OP

-TEE

OS

Trusted Application

1

Trusted Application

2

Security Service

ARM TrustZone-enabled Chipset

Individual Application Space

TEE Core

HAL

Internal API

TEE Functions

OP-TEE ClientTEE Supplicant

Client API

Figure 4.1: OP-TEE software architecture [112].

Figure 4.2: OP-TEE secure storage architecture [14].

In section 3.3, where the requirements of the GlobalPlatform’s TEE Internal Core API for the securestorage were presented, a possible implementation of the secure storage was also mentioned. Morespecifically, it was referred the use of the Normal World’s file system for the secure storage space.OP-TEE provides a similar implementation. In Figure 4.2 it is represented the process of updatingthe data and sending it back to the Normal World. Once the TA has the new data to be written, itwill invoke a System Call through the Internal API, which in turn will invoke operations in the TEE FileSystem to update the data and encrypt the whole disk sector. The encryption process is handled bya secure component called Key Manager. Then, the encrypted data along with REE File Operation3

commands are sent by Remote Procedure Calls (RPC) messages. In the Normal World, the TEESupplicant receives the messages and stores the encrypted data accordingly into the Linux File System.The reading process from the secure storage space is handled in a similar manner [113]. In the same

3Rich Execution Environment (REE) is a synonym for the Common Execution Environment.

47

Page 64: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

requirements, it was mandated the secure storage to be bound to a particular device. The OP-TEEachieves this by using a set of three different keys: the first one is called Secure Storage Key (SSK),which is a per-device key that is used to generate the second key, named TA Storage Key (TSK), whichis a per-TA key and is used to encrypt and decrypt a third key, the File Encryption Key (FEK), which isthe final key used to encrypt and decrypt the data stored in the secure storage space [113]. The ability tohide sensitive key material from the TAs itself is also guaranteed as they do not have access to the SSKkey, thus they cannot compromise the TSKs attributed to the others TAs. Lastly, OP-TEE also providesto each TA its own individual application space, which is an essential feature as it is planned to add thepossibility of using TAs with multiple purposes on the same device.

4.3 Implementation

In this section, it is explained in more detail the implementation of the proposed TrustZone-backedBitcoin Wallet, which is divided in two steps. The first step consists in setting up the chosen platformin order create the ideal development environment, which includes installing the software stack and theneeded tools for a more convenient development process, as well as performing the necessary tests toguarantee that everything is working properly. The second step corresponds to the porting of the basewallet into the platform, as well as to the implementation of the improvements proposed in section 3.3.

4.3.1 Platform Configuration

The configuration of the ARM Juno motherboard is determined by a set of files that are located inside ofa Secure Digital (SD) card. Its content is distributed according to the following layout [114]:

• MB: This is a folder that contains the motherboard firmware, such as the Basic Input/Output Sys-tem (BIOS), the Input/Output Field Programmable Gate Array (IOFPGA) image, and the PowerManagement Integrated Circuit (PMIC) configuration. As the ARM Juno board has three revisions,there are three sub-folders: HBI0262B for the Juno-r0, HBI0262C for the Juno-r1, and HBI0262Dfor the Juno-r2. Each folder contains the motherboard firmware specific to its revision. However,the last one is the only one that needs to considered in this configuration;

• SITE1: It is a folder that has all the configuration files for the SoC. It has the same structure as theMB folder for each revision;

• SOFTWARE: A folder that includes the SoC software images. A few examples are the SystemControl Processor (SCP) Firmware, ARM Trusted Firmware, Unified Extensible Firmware Interface(UEFI), Linux, and RAMDisk;

• config.txt: It is a file that contains some general configurations of the ARM Juno motherboard.

Whenever, the configuration of the ARM Juno motherboard is changed the content of the SD cardshould be modified accordingly. Besides the default motherboard configuration, the board does notprovide any file system by default. If one is to be used, it should be included in an Universal Serial Bus(USB) storage device, which is then attached to the board. ARM provides documentation on how to getand setup the compatible file systems [115]. For the implementation of the presented proposal, it wasopted to use the Linaro Tracking Kernel (Latest) with OpenEmbedded LAMP filesystem [115], as it hadthe most recent kernel along with the most functional file system [116].

With the file system installed in an USB storage as instructed by ARM [115], it became possible toadd the OP-TEE software stack. At the early stages of this dissertation, the version of OP-TEE that was

48

Page 65: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

available was the version 1.1.0, whose installation required to cross-compile4 all the software stack thatwas provided in a set of different repositories stored on Github [14], and then to update the SD card andthe file system with some of the files that resulted from the compilation process.

The repositories in which the software stack is found were the following:

• arm-trusted-firmware: This repository provides a reference implementation of the Secure Worldsoftware, which includes the Secure Monitor, as well as some interface standards, such as thePower State Coordination Interface (PSCI), Trusted Board Boot Requirements (TBBR) and SMCCalling Convention [117];

• linux-linaro-tracking: This is the repository that contains the Linux kernel with the modificationsmade by Linaro;

• optee_os, optee_client, optee_linuxdriver, and optee_test: Repository that contains the source-code of the software that was described in section 4.2.

Unfortunately, the setup to install the existent version into the ARM’s Juno board was broken, as itwas mentioned by the following warning posted in the OP-TEE’s Github page [118]: “Warning! This setupis currently broken, bl30.bin and bl33.bin doesn’t exist on the URLs stated any longer. We are workingwith a fix and once ready, we will replace this section and instead put Juno board within the repo sectionbelow. Until resolved, we will keep the information below for reference”. The problem that was describedindicated that the SCP runtime image (bl30.bin) and the UEFI firmware (bl33.bin) were not availableanymore in the usual sURLs used by the script. As it was referred before, certain files are needed toconfigure the Juno motherboard, and should be included in the SOFTWARE folder because they are partof the SoC software images. As a solution to this problem, firstly previous versions of the missing filestaken from pre-built binaries were used, more precisely the ones from version 16.01, released in January,2016 by Linaro [119], as they were the most recent ones at the time. The instructions to download thesource-code of the remaining files of the OP-TEE software, and compile them for the ARM Juno boardwere available, once again, at OP-TEE’s Github page [118]. However, after the download process, andduring the compilation, the two following errors appeared:

1. tee_shm.c:365:14: error: macro “dma_buf_export” passed 5 arguments, but takes just 4:This was an error associated with a macro whose signature differs between the two Linux kernelsversions. The older ones use five arguments, while the more recent ones only need four of them.The fix for this problem was simple and consisted in removing the fifth argument, which was 0, andit is unnecessary to the kernel that was currently being used.

2. No rule to make target ./devel/juno_optee/optee_os/out/arm32-plat-vexpress/core/tee.bin,needed by build/juno/debug/fip.bin: This problem appeared when the fip.bin file was being cre-ated, which is the firmware image package, and as such it needs the binary of the TEE (tee.bin) tobe compiled. The localization of the latter file was predefined to a subdirectory of the arm32-plat-vexpress folder, however that folder did not exist. Instead, the file was in a subdirectory of a foldercalled arm-plat-vexpress, which was then used to replace the predefined folder in the compilationscript.

After solving these two problems, the software stack was successfully compiled. The next step wasto update the SD card and the file system with the some of the files that resulted from the compilation

4Cross-compile is the process of using compiler running on a host and produce executable code for a target different from thehost. In this specific case, the host would be a Linux machine where code is compiled, and the target would be the ARM Junoboard, which is were the code will be executed.

49

Page 66: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

process as mandated by OP-TEE [14]. However, once that was done, the board would always beinterrupted during the booting process. The reason for that to happen was related with the missing filesthat were replaced, which were not compatible with the remaining files that were on the SD card or onthe file system. To remove this incompatibility problem, it was analyzed the content of every file that wasin the pre-built binaries, in order to find useful information about the versions of the files that were usedupon the creation of the same binaries. A file named juno-latest-oe-uefi-20160125-1708.txt, containedabbreviated hashes (the first few hexadecimal characters) of the last commit5 that was made for everyrepository that was used.

Regarding OP-TEE, there was only information about three of the repositories that were used,namely optee_client, optee_linuxdriver, and optee_os. Nevertheless, using the available information,it was searched the complete hashes (all the hexadecimal characters) of the mentioned repositories.Once they were found, they replaced the existent ones on the OP-TEE compilation script. After thesemodifications, the OP-TEE’s software stack was compiled again, and the needed files were updated.However, the problem persisted, the board would still be blocked in the middle of the booting process,which meant that the incompatibility was not related with the files of the updated repositories, but thewith remaining ones. As there were not any additional information about them. The same procedure, ofreplacing the missing files, was also applied with multiple configurations, where different versions of themissing pre-built binaries were used, but the end result was always the same.

Finally, on April 1st, 2016, it was released the version 2.0.0 of the OP-TEE software stack. Thisrelease included a brand new way of compiling the source-code for the ARM Juno board. Therefore, italso had a new associated script. Previously, it was mentioned that there were some files that shouldbe updated in the file system, but as described, there were some incompatibilities between the versionsof the files that were used. In this way, with the new approach, OP-TEE opted to use an internal filesystem that was built during the compiling process and integrated in the ramdisk.img file6. The previousproblems that resulted during the compiling process no longer appeared. Instead, the following warningwas shown:

• WARNING: It wasn’t possible to open optee.ko and optee_armtz.ko for read: The optee.koand optee_armtz.ko files are the kernel modules that are used to implement the OP-TEE LinuxDriver. After a brief analysis of the source-files, it was noticed that those files did not exist. In fact,none of the files related with the optee_linuxdriver repository was there. Consequently, the mod-ules could not be opened for read. However, if these modules were not included in the compiledfiles, the OP-TEE Linux Driver would not work. Thus, to solve this problem, the optee_linuxdriverrepository was compiled and downloaded separately. Then, the resulting files were added to theoriginal source-files. Afterwards, the compilation script would no longer produce the same warning.

A few days after the release of the version 2.0.0 of the OP-TEE software stack, the respective docu-mentation was provided [120], and it mentioned that the optee_linuxdriver would not be used anymore,because a completely new generic TEE drivers would be adopted, which would be included in the kernelby default. This was the reason why the optee_linuxdriver repository was not included in the source-filesof this version. The warning only appeared because some verifications that were used in the previousversions were not removed. Nevertheless, the compilation process was successful and the files for theSD card were updated without any problem. Fortunately, the board no longer was blocked during thebooting process. The next step described in OP-TEE’s Github page [14], was to run the tee-supplicant,which was included in the compiled software and transferred to the SD card. However, when executingthe command to run it, a new error appeared:

5Every time a repository is updated in GitHub, it is attributed an unique identifier, which is a hash that resulted from use of theSHA function upon the whole repository. This process of updating is called commit.

6ramdisk.img, is an image that is mounted by the kernel at boot time. It contains an initial root file system.

50

Page 67: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

• TEES:main:376: failed to find an OP-TEE supplicant device: This error means that the tee-supplicant could not find the generic drivers that were built-in directly into the kernel. There aretwo generic drivers, both are generated during the booting of the kernel, and are located in the devfolder of the file system. More precisely, their full path is /dev/tee0 and /dev/teepriv0 [121].

The reason why the supplicant could not find the generic drivers was unknown, until it was discussedwith the OP-TEE developers [121]. It was concluded that the OP-TEE node in the device tree7 wasmissing, which meant that its firmware was not recognized by the board. This problem was neverdetected because the software stack was never tested on the most recent revision of the ARM Junoboard, but only on the previous ones. Unfortunately, no solution was provided. Nevertheless, enoughinformation to find one was given. The file juno.dts, which was mentioned in the discussion, consistedin the device tree file of the first revision of ARM Juno board (r0). When searching for the device treefile for the revision of the used board, it was detected that it was missing from the source-files. The onlyother existent device tree file was for the second revision (r1). Thus, after some research and analysisof the content of mentioned files, it was realized that it was possible to create the file for the last revisionby modifying the one from the previous revision. For example, there are only a few differences betweenthe ARM Juno-r1 and ARM Juno-r2 boards, the main one resides in the processors that are used. Thus,part of the implemented solution was to make a copy of the juno-r1.dts file, and modify it according to theARM Juno-r2 board hardware. To complete the solution a binary of the modified file was still needed tobe included in the SD card, as it was one of the files that should be updated. To generate it, the Makefilethat processed existent device tree files was modified to include the new one that was modified. Afterthis process, the whole software stack was compiled again following the same instructions as before,and the needed files were updated once more. Finally, the board booted successfully. Moreover, thetee-supplicant, found the new generic drivers making the board operational with the OP-TEE softwarestack. All this procedure was reported back to the OP-TEE developers [121], and the proposed modifiedfile was also provided, which lead to the integration of this solution natively into the OP-TEE project [15],so it could support the ARM Juno-r2 board natively.

With the OP-TEE software stack correctly installed in board, it was possible to initiate the devel-opment process of TAs, including the ones that would implement the proposals made in section 3.3.However, to confirm that the software was working properly, it was decided to implement a general pur-pose TA first. The GlobalPlatform’s TEE Client API specification has an appendix with an example codethat can be used as a CA that implements the fundamental principals discussed in the same API. Takinginto account the provided code, it was developed the corresponding TA, where the requested functionswere implemented. One of the operations that was requested consisted in generating a cryptographickey, and in a later stage use is to perform an encryption operation. According to the GlobalPlatform’sTEE Internal Core API, whenever it is intended to securely store a key into the file system, PersistentObjects should be used as the key container. In this way, the operation flow consisted in storing thegenerated key into a persistent object, which in turn was stored in the secure storage space. Then,when the encryption operation was to be performed, the stored object would be fetched to the SecureWorld, and the key extracted and used. When this function was tested, it was noticed that the key wassuccessfully generated, but it was not correctly stored on the persistent object, because when the keywas extracted and used the encryption operation failed. After a thorough assessment of the TA devel-oped, it was confirmed that it was correctly implemented. Thus, this matter was reported to the OP-TEEdevelopers [16] along with the TA code that was used to detect the problem. Later, the origin of theproblem was identified: it consisted in the fact that important key information was not properly stored.The provided code was also integrated into the OP-TEE test case [17], and it is now used to verify the

7The device tree files specifies the hardware configuration of the board to the kernel.

51

Page 68: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

correct functionality of the OP-TEE software stack. All the remaining requested functions by the CAwere implemented and tested successfully, thus it was considered that the most critical features of thesoftware stack were working properly.

Nevertheless, during the development of previous TA it was realized that its associated developmentcycle, when using the ARM Juno board with the OP-TEE software stack, was not the most appropriate.It started with writing the source-code, followed by the compilation of the TA, and then its integration intothe OP-TEE’s file system. As the file system is included in the ramdisk.img file, the TA must be placed inthe software stack source files. After including it, the software stack must be compiled again so that thefile system with the TA is included in the ramdisk.img file. Then, the SD card must be updated with thenew generated files. The problem with this approach is that every time a change is made within the TA,it is needed to repeat the whole process, which is very time consuming. Moreover, as the OP-TEE onlyprovides the bare essencial, it does not include the possibility of using the SSH and SCP.The additionof those features would allow to simplify the development cycle of the TAs, as their integration could nowbe done without the need of recompiling the software stack and to update the SD card. What’s more,it would create the possibility to develop and test applications remotely, which up until now it was notpossible with the current setup.

In this way, and to efficiently develop TAs, support for the SSH and SCP features was added. Aftera careful research, it was found that the Dropbear [122] software package was a good option to beused along with the existent software stack, as it was design to provide a SSH server and client to plat-forms with low memory and computational resources making it an ideal solution for embedded devices.The process of configuring, compiling and installing Dropbear was described as to be quite simple.However, for the current setup, several problems were encountered during that process. The first prob-lem was related with the Internet connection on the ARM Juno-r2 board, which was done through theuse of the Ethernet port, but for some reason the board could not have access to the Internet. Afterperforming some tests, it was verified that the eth0 interface did not have an attributed IP address.Moreover, there was not any static route defined. In order to solve the problem, those configurationswere made manually: to set the IP address, and to set the route the ifconfig and route commands wereused. Another problem that was found resulted from the cross-compilers used to compile the Dropbearsource-code. Firstly, the same ones that were used to compile the OP-TEE software stack were used:gcc-linaro-aarch64-linux-gnu and gcc-linaro-aarch32-linux-gnu, but the resulted binaries did not work onthe ARM Juno-r2 board. A numerous of different cross-compilers and configurations for Dropbear wereused without success. There was one compiler, arm-linux-gnueabi-gcc, that partially worked: the Drop-bear was compiled and installed successfully into the board, but whenever the SSH server received aconnection, it would reject it by affirming that the login attempt was performed by a nonexistent user.This happened because the resulting binaries were static and some of the needed libraries were notincluded, thus it could not recognize the user. From this point on, it was adopted a new approach whereit was searched for a cross-compiler that would indeed include the necessary libraries to the binariesthat it generated. One of such compilers was the arm-buildroot-linux-uclibcgnueabi-gcc, which couldbe obtained by using BuildRoot 2016.02[123], that consists in a set of Makefiles that allow to generatea defined cross-compiler. After compiling the Dropbear source-files with this new cross-compiler, theresulted binaries were integrated into the existent software stack on the ARM Juno-r2 board, and finallythere was the possibility of using the SSH and SCP features. All the process taken to generate the finalbinaries was documented and made available so that every developer could benefit from these features.[22, 23].

As part of the OP-TEE development process, the cross-complier that was used to compile the filesthat would update the SD card, was upgraded to the GCC 5, and that change required a copy ofquite a few more files than before to the file system. As a consequence, there was an increase of

52

Page 69: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

the ramdisk.img file size that exceeded its predefined Juno memory flash reserved location, it changedfrom 7.85 MB to 29.15 MB. Thus, it became impossible to use the OP-TEE software stack in this state[18]. To get around this size limitation, the addresses that defined where the images were loaded intothe Juno’s flash memory were modified and rearranged. The file that contained those addresses wascalled images.txt. The methodology followed for the modification of the addresses was: i) Analize andunderstand the structure of the images.txt file; ii) verify how the flash memory is distributed betweenthe images described in the file; iii) change the addresses by calculating the minimum amount of spaceneeded for each one of the images, until enough space is available for the ramdisk.img; and iv) updatethe images.txt file with the new calculated addresses. Fortunately, the setup was operational and prop-erly working again, which lead to share the changed addresses with the OP-TEE developers [19], andnow they are part of the instructions to get and build the OP-TEE software for the ARM Juno board,which are available on the OP-TEE’s GitHub page [20] and on the OP-TEE official website [21].

4.3.2 Implementation Details

As it was mentioned in section 3.2, the source-code of BitSafe is essentially platform independent, withthe exception of a few functions that are related with the direct interaction with the platform’s peripherals.Therefore, the porting process of BitSafe’s source-code to a different platform from the one for which itwas originally designed consists only of implementing those dependent functions. A description of thesefunctions was also given in Table 3.6. Some of them are related with the presentation of informationto the user, while others are meant to process the information received from the user. There are alsofunctions that are responsible for writing and reading from the platform’s storage.

The ideal implementation for the functions that present the information would be through the usageof the GlobalPlatfrom’s Trusted User Interface API, which is targeted at devices that have a touchscreen,display or keyboard wired and integral to the platform [31]. This API provides a way of securely displayand receive sensitive information with the guarantee that it was not maliciously modified. The ARMJuno-r2 board supports the use of a Liquid Crystal Display (LCD) screen and keyboard. However, asmentioned in section 4.2, OP-TEE does not provide an complete implementation for it. Neverthelessthere has been a growing effort in that direction [124]. Since this project is not yet finished, it is notpossible to benefit from the GlobalPlatfrom’s Trusted User Interface API. In this way, and to reduce thecost of the developing process, it was opted to not use a display and keyboard wired and integral tothe platform, but instead it was decided to use the board’s Universal Asynchronous Receiver/Transmitter(UART) port, with the settings indicated by ARM [114]: Baud rate: 115200, Data bits: 8, Parity bits:None, Stop bits: 1. In this way, the functions: streamPutOneByte(), newOutputSeen(), setTransaction-Fee(), clearOutputSeen(), displayAddress(), userDenied(), displayOTP(), and clearOTP() will use thehost’s screen to display the information, and the function streamGetOneByte() will use information intro-duced in the host’s keyboard by the user. Nevertheless, it is important to notice that this configurationis only used for development purposes. If this version were adapted to be used commercially, the Glob-alPlatfrom’s Trusted User Interface API should be exploited as it was proposed in section 3.3. Moreover,as the solution that is presented in this dissertation is mostly platform-independent, it could be transferedto a platform that provides an implementation for that API.

Regarding the functions nonVolatileRead(), nonVolatileWrite(), and nonVolatileFlush(), which shouldact upon the platform’s storage, they will in fact operate on the write-cache that was proposed in thesection 3.3. This cache is fully implemented in the Secure World, and as it was descried, it consists ina buffer with the size of a disk sector, where the data that comes from the Normal World is written. Ifthe disk sector correspondent to the one where the data is supposed to be written is already loaded onthe buffer, the buffer is updated with the new data. Otherwise, the disk sector that is currently on the

53

Page 70: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

buffer is flushed into the secure storage, and the correct disk sector is loaded, and only then the bufferis updated with the received data. The size of the buffer was chosen to be the same as the size of adisk sector, because for most storage devices it is faster to update an entire sector than only a portionof it. The implementation of this cache was based on the ones that were available for the platforms wereBitSafe was tested by its original authors.

Meanwhile, the storage is implemented by using the GlobalPlatform’s TEE Internal Core API. In thisAPI it is indicated that the secure storage stores Persistent Objects. Each one of them has an associatedData Stream, which can store large amount of data. In this way, BitSafe’s storage is a data stream of apersistent object, which includes all the partitions depicted in the Figure 3.1. The size of the data streamwas set using the function TEE_TruncateObjectData() to be the same size as the BitSafe’s storage.Whenever the cache needs write data into the storage it uses the function TEE_WriteObjectData(), andwhen it wants to read data from the storage it uses the function TEE_ReadObjectData().

For the hardwareRandom32Bytes(), it is also used one of the functions provided by the GlobalPlat-form’s TEE Internal Core API, namely the TEE_GenerateRandom() function. The implementation ofthis function uses an hardware True Random Number Generator (TRNG) whenever the platform whereit is implemented on provides it. The ARM Juno-r2 board includes a “Trusted Entropy Source” whichprovides 128-bit random numbers, which, however, was not being exploited by the OP-TEE developers[125]. instead a Pseudo-Random Number Generator (PRNG) named Fortuna [126] was used to gen-erate cryptographically strong pseudo-random numbers. It is expected that newer versions of OP-TEEmake use of this entropy source.

In section 3.3, it was also proposed to transfer all the cryptographic operations to the Secure World.Most of them were implemented using the GlobalPlatform’s TEE Internal Core API, which requires anoperation handler that is obtained by using TEE_OperationHandle. This handler is then used as anargument for the subsequent function calls. The SHA with 256 bits, AES, and HMAC - SHA with 256and with 512 bits are specified in the API as multi-staged operations, in which one function is usedto initialize the operation, another to feed it with data and another to finalize it. For SHA with 256bits, TEE_DigestUpdate() and TEE_DigestDoFinal() were applied (there is no initializer function); forAES, TEE_CipherInit(), TEE_CipherUpdate() and TEE_CipherDoFinal() were used; lastly, for HMAC -SHA with 256 and with 512 bit, TEE_MACInit(), TEE_MACUpdate() and TEE_MACComputeFinal() wereused. For the remaining cryptographic operations, OP-TEE provided implementations for the PBKDF2and ECDSA functions, but the former was an extension of the GlobalPlatform’s TEE Internal Core API,so other implementations of the TEE might not have it, whereas the latter one is only supported byfew implementations of the TEE. Since this proposition was designed to be as platform independent aspossible, while still providing high levels of security, these operations were manually extended to theSecure World. For the RIPEMD with 160 bits, as it was not available in any API, its source-code wasalso ported to the Secure World. The same rationale was applied to the HMAC - DRBG.

The General Wallet Functions were implemented by porting the corresponding original code to theSecure World, by implementing the necessary adaptations and using the previous functions when re-quired. The core of those functions remained the same, and the required modifications resulted fromthe fact that not all the libraries that are available in the Normal World are provided in the Secure World.For example, the printf() C function is not implemented.

Another important aspect of the implementation is the communication between the Normal Worldand the Secure World for when performing an operation. The process flow was already described inthe subsection 2.1.3, however it was not mentioned which were the functions that were used from theGlobalPlatform’s TEE Client API specification. There were few options available to allocate the region ofmemory that would contain the arguments of the operation, but the method chosen consisted in creatinga buffer in the Normal World with the arguments of the operation, and reference it using a structure called

54

Page 71: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

TEEC_TempMemoryReference, which is provided by the mentioned API. This specialized structure issent to the Secure World through the TEEC_InvokeCommand() along with other important informationrelated with the operation, such as the size of each one of the arguments.

Lastly, as it was indicated in subsection 2.1.1, the applications that request the execution of opera-tions from the TAs are usually known as CAs. During the implementation of the functions previously men-tioned in this section, every function in the Normal World that had code related with the communicationwith the Secure World, was isolated into a single file, thus creating an unique CA, named tz_functions.c.The same principle was applied in the Secure World, where all the functions were grouped into a singleTA called wallet_ta.c. There were two main reasons for this isolation. The first one is because it makesit easier to analyze and scrutinize the code of the functions that were designed to communicate with theSecure World and to execute the critical operation in a secure environment. The second reason is be-cause it allows to isolate all the code that has to known about the GlobalPlatform’s APIs and libraries. Inthis way, duplicated code was removed, while at the same time providing a more structured and modularsolution. This lead also to some minor adaptations to the structure of the original source-code, creatingan easier to understand and more organized source-code. As a final remark, the final source-code of thedeveloped TrustZone-backed Bitcoin wallet will be made publicly available on the 21st of October (dueto procedures related with the submission of a paper for the ICISC conference), and in the meantimecan be accessed in [127]. Regarding to source-code of the resulted TA mentioned in subsection 4.3.1,which was developed for the example provided in the GlobalPlatform’s TEE Client API specification, ismade available as open-source and can be consulted in [128].

4.4 Experimental Results

In this section, a performance analysis to the modules presented in Figure 3.3 is performed, where theWallet Storage, Cryptographic Operations, and General Wallet Functions are assessed according tothe configurations presented in sub-figures 3.3.a) and 3.3.b). In other words, the original code whichwas ported into the ARM Juno-r2 board with the configuration depicted in Figure 3.3.a) is comparedagainst the developed wallet with the configuration depicted in Figure 3.3.b). From this point on, theformer will be denoted with the term Original Base Wallet (OBW), while the latter will be denominatedTrustZone-backed Bitcoin Wallet (TBW).

The methodology used to measure the performance of each component consisted in sampling itsexecution time, which is acquired through the use of the clock() function from the C native library, onehundred times, and then computing their median. This method was chosen because during the de-velopment of this dissertation there were no native profiling techniques available provided by OP-TEE.Thus, it is important to mention that the execution times presented in this chapter for the TBW include,besides the CA calls, the overhead of the communication between the Normal World and the SecureWorld, enabling the exact assessment of the overhead imposed by the TrustZone technology. It is alsoimportant to remind that the main goal of developing the TBW was not to improve the execution times ofthe functions provided by the OBW, but instead to improve their security.

The Wallet Storage is the first module to be analyzed, and as it is constituted by the two partitions thatare presented in Figure 3.1, the evaluation of writing and reading operations is executed independentlyfor each one of them, considering their full length, for both OBW and TBW. More specifically, for theGlobal Partition 512 bytes are read and written, and for the Accounts Partition 1024 bytes are read andwritten. In the case of the TBW, due to the write-cache proposed in section 3.3, and whose details weregiven in subsection 4.3.2, two possible scenarios were considered for when reading and writing data intothe secure storage space. For the write operation, as it always writes directly into the cache, the situationwhere the correspondent disk sector is already loaded was evaluated, as well as the other where it is

55

Page 72: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

not, and as such it needs firstly to be fetched. Regarding the read operation: if the correspondent disksector is already in the cache, the data is read directly from there, otherwise, it is read from the securestorage space. In this way, to perform a complete analysis of this module for the TBW, the performanceof the write and read operations are measured for all the possible mentioned scenarios. In addition, theoperation of flushing the cache’s data into the secure storage space is also assessed.

Table 4.3: Execution time of storage related functions. The values are presented in clock cycles. Inparenthesis the execution time increase in percentage of the TBW relative to the OBW is presented.

Function OBWTBW

Secure Storage Secure Storage + Write-Cache (block not loaded)

Secure Storage + Write-Cache (block loaded)

Write in Global Partition(512B) 34 129111 (+374136%) 106685 (+309133%) 128 (+271%)

Write in AccountsPartition (1024B) 25 129724 (+518798%) 131833 (+527232%) 138 (+454%)

Read from GlobalPartition (512B) 20 99255 (+496177%) 99485 (+497325%) 128 (+540%)

Read from AccountsPartition (1024B) 6 99680 (+1661241%) 99901 (+1664925%) 136 (+2166%)

Flush data 4 N/A 178734 (+4468262%) 1787345 (+4468262%)

In Table 4.3 the results of the execution for the aforementioned storage operations are presented.Regarding the OBW, it should be noticed that the execution times of the read and write operations on theAccounts Partition are smaller than the ones associated with the Global Partition, even though the formeris larger. This is related with the fact that the Accounts Partition is fully included in one disk sector, whilethe Global Partition is divided between two disk sectors. Therefore, when writing 1024 bytes of data intothe former partition, the whole disk sector can be replaced directly8. However, when writing 512 bytesinto the latter partition, the two whole disk sectors needs to be loaded, the respective data replaced, andafterwards the both whole sectors are written back on disk. The same principle applies to the readingoperation. This situation does not apply to the TBW, due the way that the storage is implemented. Theuse of a Data Stream to store the whole BitSafe’s storage implies that whenever one intends to read orwrite it is needed to fetch the Persistent Object that has the Data Stream independently of the targetpartition. Moreover, as OP-TEE OS defines the disk sector size to 4096 bytes long, along with the factthat it stores the data aligned in memory [113], allows to fetch the one disk sector that contains theBitSafe’s storage into the write-cache. Thus, the execution time of the writing of 1024 bytes into theAccounts Partition can never be less than the execution time of the writing of 512 bytes into the GlobalPartition, because now the writing operation only depends on the size of the data to be written. Whencomparing the TBW with the OBW, it is visible that there was an increase in the execution time for thestorage functions, but that was expected as the secure storage space adds an extra layer of encryptionprovided by the Secure World [113]. When the secure storage space is used directly, the overhead ofthe additional encryption process has a significant larger impact. After adding a write-cache, the effectof the overhead is greatly mitigated if the requested block is already in memory; otherwise, one has toupdate the cache, with the associated overhead of reading from or writing to the secure storage. Inboth cases, there is not any work around to improve the Flush data function, as it writes directly into thesecure storage, where the entire correspondent disk sector must be decrypted first, then data is writtenfrom the write-cache and finally the disk sector is encrypted and flushed to the secure storage space.

For the Cryptographic Operations, only the functions that are directly used by the General Wallet8Here it is considered that the 1024 bytes to be updated are located in a single disk sector

56

Page 73: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

Functions and the Wallet Storage modules were assessed, namely: the SHA with 256 bits, HMAC- SHA with 512 bits, AES with 128 bits, ECDSA, PBKDF2, and RIPEMD with 160 bits, which weremeasured by executing the operation. The remaining operations: SHA with 512 bits, HMAC - DRBG,and HMAC - SHA with 256 bits were measured indirectly as they are only used as subroutines by thepreviously mentioned operations, as it is depicted in Figure 3.2. The SHA with 256 is one of the mostused Cryptographic Operations in the whole wallet, since it is used in multiple situations, including thecomputation of Bitcoin addresses, where two iterations of the algorithm are required. Thus, in order tohave a better understanding of how it performs under different conditions, its execution was analyzedfor different argument sizes in all of the operation stages, more precisely with 1 byte and with 100 bytesof data. Moreover, a special mode (FINISH-DOUBLE), where a full iteration of the SHA operation isapplied after a first execution, was also assessed.

Table 4.4: Execution time of the used Cryptographic Operations. The values are presented in clockcycles. In parenthesis the execution time increase in percentage of the TBW relative to the OBW ispresented.

Function Mode OBW TBW

SHA-256

INIT (100B) 2 69 (+3350%)

WRITE (100 B) 43 121 (+178%)

FINISH (100 B) 30 122 (+306%)

FINISH-DOUBLE (100 B) 65 134 (+106%)

INIT (1 B) 2 68 (+3300%)

WRITE (1 B) 2 114 (+5600%)

FINISH (1 B) 35 122 (+250%)

FINISH-DOUBLE (1 B) 70 134 (+91%)

HMAC-SHA-512 SET OPERATION KEY 199 140OPERATION (69 B) 173 (-13%)

AES-XEX-128 DECRYPT (64 B) 794 157 (-80%)

ENCRYPT (64 B) 364 157 (-56%)

ECDSA SIGN 1280540 190499 (-85%)

PBKDF2 - 203447 34422 (-83%)

RIPEMD-160 OPERATION (32B) 32 153 (+378%)

In Table 4.4, the performance of the Cryptographic Operations directly used in both OBW and TBW ispresented. The SHA with 256 bits and the RIPEMD with 160 bits were the only ones that were negativelyaffected for being executed in the Secure World. Regarding the SHA with 256 bits, is important to notethat the execution time of the WRITE stage in the TBW is practically independent of the data size thatis being processed. The AES in XEX mode with 128 bits function benefits from the same principle, asthe encryption and decryption processes take the same time to execute in the TBW as opposed to whathappens in the OBW. Moreover, it was proven to be much faster when the API provided by OP-TEEfor the Secure World was used. This confirms that the use of standardized APIs is beneficial to obtainthe maximum performance, since each vendor is able to implement the functions in the most optimizedmanner for the underlying hardware. The ECDSA and PBKDF2 where both manually implemented inthe Secure World and their execution time has also improved largely. The RIPEMD with 160 bits was anexception, because despite of being also manually implemented in the Secure World, its execution didnot improve. The reason behind it, is the additional overhead inherent with the communication betweenthe Secure and Normal worlds, since the code was ported from the OBW, the implementation remainsthe same, and thus, the execution times should be similar. Lastly, the HMAC - SHA with 512 bits is

57

Page 74: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

an operation that can be seen as the aggregation of two sub-operations: i) one that consists in settingthe key that will be used in the operation, and ii) the execution of the operation itself. In the OBW,both sub-operations were implemented together, while in the TBW they were separated. The motivationthat lead to its separation was that in some functions this operation is successively called, and as mostof them use the same key, it becomes more efficient to execute the operation separately from the keysetting. Moreover, as the execution time of the OPERATION is faster in the TBW than in the OBW, whenOPERATION is called repeatedly, the overhead of key setting becomes negligible and the TBW moreefficient than the OBW.

As the functions implemented by the components included in the General Wallet Functions moduleare used to provide the functionalities associated with the packets described in Table 3.7, the processingof those packets will be assessed instead. The measurements comprise the period of time since a packetis sent until a response is received, which includes the time of the communication through the UART.

Table 4.5: Execution time of the available packets. The values are presented in clock cycles. In paren-thesis the execution time increase in percentage of the TBW relative to the OBW is presented.

Packet OBW TBW

PACKET_TYPE_INITIALIZE 122 302 (+148%)

PACKET_TYPE_PING 27 53 (+96%)

PACKET_TYPE_DELETE_WALLET 3804 2728645 (+71621%)

PACKET_TYPE_NEW_WALLET 379504 3022605 (+696%)

PACKET_TYPE_NEW_ADDRESS 5640665 2159050 (-61%)

PACKET_TYPE_GET_NUM_ADDRESSES 29 100 (+245%)

PACKET_TYPE_GET_ADDRESS_PUBKEY 1126475 167978 (-85%)

PACKET_TYPE_SIGN_TRANSACTION 1348990 296758 (-78%)

PACKET_TYPE_LOAD_WALLET 206596 652153 (+215%)

PACKET_TYPE_FORMAT 10373 6900920 (+66427%)

PACKET_TYPE_CHANGE_KEY 206123 897592 (+335%)

PACKET_TYPE_CHANGE_NAME 2244 329466 (+14582%)

PACKET_TYPE_LIST_WALLETS 14108 1994975 (+14041%)

PACKET_TYPE_BACKUP_WALLET 108 230 (+111%)

PACKET_TYPE_RESTORE_WALLET 412764 1961605 (+375%)

PACKET_TYPE_GET_DEVICE_UUID 65 99506 (+152986%)

PACKET_TYPE_GET_ENTROPY (32B) 440 529250 (+120184%)

PACKET_TYPE_GET_MASTER_KEY 1126385 698048 (-38%)

In Table 4.5 all the available packets that can be used by the host to request the wallet to executean operation are presented. As it was expected, all the functions that directly involve reading or writingto the secure storage space had its execution time increased. For example, the function to format thestorage was one of the most impacted as it performs multipass, low-level overwrites with random datain the full size of the wallet to guarantee that its final state is unpredictable, leading to a large overheadfrom the additional encryption layer. The functions to delete a wallet suffer from a similar issue, as itexecuted the same process but only in the specific region of the Accounts Partition where the walletto delete is stored. On the other hand, the functions that do not directly use the secure storage space

58

Page 75: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

had its performance improved. These reduced execution times result from the improvements previouslydescribed in Table 4.4. Furthermore, the functions involved in creating a new address and to sign atransactions are among the most important and used ones in the whole wallet, and the fact that thesefunctions were able to execute in a faster and more reliable manner confirm the validity of the proposalpresented in this dissertation.

Lastly, in Table 4.6 a qualitative comparison between the OBW and the TBW is presented. Firstly, theOBW storage encryption was supported on a password provided by the user. As this type of systems canoften be attacked using dictionary-based attacks, the decision to use TrustZone secure storage greatlyboosted security by encrypting data using a random key that is only available at the hardware level.While some care had been taken while the OBW was developed regarding side-channel attacks, theOP-TEE API was implemented taking into account the underlying hardware, which allows to provide anhigher level of assurance against side-channel attacks. Furthermore, while the OBW used checksums toprotect against data tampering, with TrustZone, code is also verified for integrity at boot-time. Moreover,TrustZone allows for the co-existence of multiple TAs, with high assurance that none will interfere witheach other. Therefore, it is possible to extend the proposed wallet with other applications that need highlevels of security, such as home-banking. Finally, it was seen that while the use of the secure storagedeteriorated performance for some functions, the use of the OP-TEE API allowed for platform-specificoptimizations that enhanced performance for cryptographic operations.

Table 4.6: Qualitative comparison between the OBW and the TBW.

Resistance againstdictionary attacks

Resistance againstside-channel attacks

Code and dataintegrity Extensibility Performance

OBW 7 3 3 7 33

TBW 33 33 33 3 3

4.5 Summary

In this chapter, the details for the implementation of the proposed improvements made in section 3.3were described. As they exploited TrustZone features, a TrustZone-enabled platform was needed. Inthe process of choosing one, the processors that supported the TrustZone technology were analyzed.There are several end-consumer platforms that contain the presented processors, but most of them stillhave TrustZone development blocked by the OEMs. Thus, it was opted to use a development platform,as they allow to make full use of its features. After an analysis of the currently most used developmentplatforms for creating, testing, and debugging TAs, the ARM Juno-r2 board was chosen as the mostsuitable one to implement the base wallet. This platform was produced by ARM to offer developers achance to research on emerging architectures, that will be available on modern SoCs.

As previously mentioned in subsection 2.1.1, to use the full potential of the TrustZone technology,a Trusted OS should be features in the Secure World. In its default state, the ARM Juno-r2 board didnot include one, so the OP-TEE was used, which provided an implementation for OSs of the Normaland the Secure world. Moreover, this was an open-source project that had implemented the standard-ized GlobalPlatform APIs, which facilitate the development of platform-independent applications, whileoffering optimal performance.

The process of installing the OP-TEE software stack on the ARM Juno-r2 board was not standard-ized, and hence modifications were required to the traditional installation process. All the changes andproblems that surfaced from that process were described, as well as the solutions found. The proposed

59

Page 76: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

changes contributed to the enrichment of the OP-TEE project, including the added native support forthe ARM Juno-r2 board and the identification of some missing features on the existent software alongwith a test case for its detection. The whole process followed to adapt the existent configuration to amore programmer friendly setup was also described, including the possibility of using the SSH and theSCP features. This created the ideal environment for developing TAs, including the one that was used tocreate the TrustZone-backed Bitcoin Wallet, for which the implementation details were presented. Also,the process of porting the OBW to the chosen board was described, as well as the functions and APIsused to take full advantage of the TrustZone features.

This chapter ended with the presentation and discussion of the execution times for the functionsthat operated upon the wallet storage, performed cryptographic operations, and executed the generalwallet functions on the original base wallet and on developed wallet. It was concluded that the readand write operations were negatively affected due the additional encryption layer provided by the OP-TEE. However, with the addition of the proposed write-cache that was greatly mitigated. Regardingthe cryptographic operations, as most of them were implemented using the GlobalPlatform APIs, whichenable platform-specific optimizations, their execution time improved, while others such as the SHA with256 bits did not, but they took the same time to process the data independently of its size.

60

Page 77: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

CHAPTER 5

CONCLUSION

Contents

5.1 Summary and Overall Conclusions . . . . . . . . . . . . . . . . . . . . . . . . 62

5.2 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

61

Page 78: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

5.1 Summary and Overall Conclusions

The main objectives of this dissertation were to improve the security associated with the currently avail-able Bitcoin wallets through the use of the TrustZone technology features, while at the same time in-creasing its functionality without compromising the security level that was added. In this way, and inorder to benefit from the enhanced security, it was intended to add the possibility of running multiplesecurity sensitive applications in the same device as the wallet, such as home-banking applications.To that end, modification were proposed to an existent wallet, and implemented in a TrustZone sup-ported platform to prove the validity of this dissertation. Moreover, the efficiency of the functions of thedeveloped wallet was also assessed.

Firstly, the TrustZone technology was overviewed as a way to identify the main features that were pro-vided. Its hardware and software architectures were described, which are underpinned by the conceptof two different virtual worlds. Each one of them has a unique vision of the SoC according to the securityrequirements associated with it the Normal World, consists in the common execution environment forthe normal applications, whereas the Secure World, which is a TEE, is where TAs are executed witha high level of integrity and confidentiality supported by the underlying hardware. Afterwards, Bitcoinwas introduced and described as a peer-to-peer network that allowed to perform transactions betweentwo ends, without recurring to a third trusted party to prevent the double-spending problem. This, as-sociated with the fact that Bitcoin is heavily based on public key cryptography to create a secure androbust payment system, makes it very attractive to the normal user, and specially to the business andfinancial sector, due the low costs that are associated with its use. A theoretical analysis allows to con-clude that the implementation of a Bitcoin wallet in a TrustZone-enabled system allows for a solution withenhanced security features, where sensitive data is processed in a manner that ensures integrity andconfidentiality. However, up until now, there is not any related work that provides experimental resultsor security analysis for such solution. Thus, this dissertation contributes to make up for the shortfall thatwas existent in this study field.

Among the different types of Bitcoin wallets available, an Hardware wallet was chosen as the basewallet type, since it had proven to be the most prone to increase its security and functionality whenused along with the TrustZone technology. For the base hardware wallet itself, the BitSafe developmentprototype was considered as the most fit because it presented features which were in agreement withwhat was intended for the final solution: the source-code was independent from the platform where it wasimplemented, and it was fully available as open-source. The next step consisted in carefully analyzing itsmain modules, namely the Storage, Cryptographic Operations, and General Wallet Functions. From thisanalysis, it became possible to identify parts of the system that could be improved, and critical sectionsthat should be executed in a more secure environment. Thus, proposals where made that consistedin transferring the sensitive operations to the Secure World to be integrated in a unique TA. Theseproposals would guarantee that the handled sensitive data, the critical operations and the stored datacould not be tampered with. It would also ensure that the integrity of the developed TA was maintained,enabling to detect any unauthorized changes. Moreover, it would increase the functionality of the walletby allowing multiple security-sensitive applications to run simultaneously in the same device withoutcompromising the level of added security. In this way, a base wallet was proposed with increasedsecurity, functionality, and trustworthiness.

To implement the proposed improvements a TrustZone-enabled development platform was needed.After an analysis of the most popular ones that are used for the development of TAs, the ARM Juno-r2 board was considered as the most suitable, mainly due its hardware which represents the future ofconsumer electronics, and as such it will eventually also be used for Bitcoin wallets. To provide theboard with the full capabilities to make the most out of the TrustZone features, the OP-TEE software

62

Page 79: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

stack was used that provides an implementation for the Normal World OS, as well as for the SecureWorld OS, with accordance to standardized GlobalPlatform’s APIs. However, the installation processof this software into the chosen board was not standard and involved some modifications to its sourcefiles, from where several contributions resulted to the OP-TEE project. This enabled to have an idealenvironment for developing TAs, and more importantly, it created the necessary conditions to port thebase wallet into the ARM Juno-r2 board and implement the proposed modifications. It is important tonote that the chosen board did not condition the implementation and development processes, as theuse of standardized APIs, along with the platform-independence of the BitSafe’s source-code, allowedto create a solution that can be implemented in any device with TrustZone capabilities.

Lastly, the execution times of the developed wallet against the base wallet were compared and dis-cussed, in order to verify the impact of the implemented proposals. The read and write operations werenegatively affected due the additional encryption layer added by the OP-TEE when storing the data intothe secure storage space. Nevertheless, this effect was mitigated through the usage a proposed cache,that holds the disk sector most recently accessed. Most of the cryptographic operations had improvedits execution time, mostly because of the use of the OP-TEE’s efficient implantation of the GlobalPlat-form’s APIs. This shows that, whereas the execution time of read and write operations were larger dueto an extra level of encryption, cryptographic operations were made more efficient through the use ofstandardized APIs, that enable vendors to implement these operations in a more optimized and securemanner.

5.2 Future Work

During the development of this dissertation it was not possible to use the GlobalPlatform’s Trusted UserInterface API as it was not yet fully developed by OP-TEE. However, the addition of this API wouldgreatly increase the security provided by the TrustZone-backed Bitcoin wallet that was developed. Insuch case, it would be possible to use a keyboard or touchscreen to have the user’s password enteredwithout the risk of having as this communication would be handled directly by a specific TA. In the samemanner, this API enables to display information in a screen guaranteeing, for example, that the value ofthe presented transaction is not tampered with.

OP-TEE also provides the option of using a different implementation of the secure storage thanthe one specified by GlobalPlatform. It allows to use the Replay Protected Memory Block (RPMB)partition of an eMMC device [129] as trusted storage which could be considered as more secure thanthe default implementation that relies on the normal world file-system. However, there is not any formaldocumentation available, and since it is has not been explored enough it is still liable to bugs. Whenthis system matures, if it becomes standardized, it could become an interesting additional feature of theproposed wallet.

Recently, due the importance of the profiling techniques, OP-TEE started to make an effort to developa benchmark framework [130] to provide with such features. Its use would allow to provide more accuratemeasures and, thus, confirm the validity of the assessment performed.

63

Page 80: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

64

Page 81: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

Bibliography

[1] M. M. Group, “Internet World Stats: Usage and Population Statistics,” "http://www.internetworldstats.com/stats.htm", August 2016, [Online] (Accessed in August 30, 2016).

[2] S. Alghamdi and N. Beloff, “Virtual currency concept: Its implementation, impactsand legislation,” in Proceedings of the 2015 Science and Information Conference, SAI2015. IEEE, jul 2015, pp. 175–183, doi: 10.1109/SAI.2015.7237142. [Online]. Available:http://ieeexplore.ieee.org/lpdocs/epic03/wrapper.htm?arnumber=7237142

[3] S. Nakamoto, “Bitcoin: A Peer-to-Peer Electronic Cash System,” p. 9, 2008, doi: DOI:10.1.1.221.9986. [Online]. Available: https://bitcoin.org/bitcoin.pdf

[4] J. Bohr and M. Bashir, “Who Uses Bitcoin? An exploration of the Bitcoin community,” in 2014Twelfth Annual International Conference on Privacy, Security and Trust. IEEE, jul 2014, pp.94–101, doi: 10.1109/PST.2014.6890928. [Online]. Available: http://ieeexplore.ieee.org/lpdocs/epic03/wrapper.htm?arnumber=6890928

[5] P. Ciaian, M. Rajcaniova, and D. Kancs, “The economics of BitCoin price formation,” AppliedEconomics, vol. 48, no. 19, pp. 1799–1815, 2016, doi: 10.1080/00036846.2015.1109038.[Online]. Available: http://www.tandfonline.com/doi/full/10.1080/00036846.2015.1109038

[6] bitcoin.org, “What are the advantages of bitcoin?” "https://bitcoin.org/en/faq#what-are-the-advantages-of-bitcoin", [Online] (Accessed in August 14, 2016).

[7] ARM, “ARM Security Technology. Building a Secure System using TrustZone Technology,” ARMwhite paper, p. 108, 2009. [Online]. Available: http://infocenter.arm.com/help/topic/com.arm.doc.prd29-genc-009492c/PRD29-GENC-009492C_trustzone_security_whitepaper.pdf

[8] S. K. Platform, “An Overview of Samsung KNOX,” White Paper, no. June, 2015.

[9] G. F. Hurlburt and I. Bojanova, “Bitcoin: Benefit or curse?” IT Professional, vol. 16, no. 3, pp.10–15, 2014, doi: 10.1109/MITP.2014.28.

[10] A. Scott, “Venezuela Will Need a Bigger Chart for Its BTC Trading Volume,” " https://news.bitcoin.com/venezuela-chart-btc-trading-volume/", [Online] (Accessed in August 14, 2016).

[11] C. Chua, “hardware-bitcoin-wallet: BitSafe Firmware.” " https://github.com/someone42/hardware-bitcoin-wallet", [Online] (Accessed in August 21, 2016).

[12] blockchain.info, “Blockchain Charts,” " https://blockchain.info/charts", 2016, [Online] (Accessed inAugust 31, 2016).

[13] ARM, “Juno r2 ARM Development Platform SoC: Technical Reference Manual,” p. 223, 2016.[Online]. Available: http://infocenter.arm.com/help/topic/com.arm.doc.ddi0515f/DDI0515F_juno_arm_development_platform_soc_trm.pdf

65

Page 82: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

[14] L. W. Security, “OP-TEE Repositories.” "https://github.com/OP-TEE", [Online] (Accessed in Au-gust 17, 2016).

[15] M. Gentilal, “Added the possibility to use optee on juno-r2.” "https://github.com/linaro-swg/linux/pull/9", [Online] (Accessed in May 26, 2016).

[16] ——, “Issues in creating and opening persistent objects.” "https://github.com/OP-TEE/optee_os/issues/785", [Online] (Accessed in May 16, 2016).

[17] P. Brand, “Test Persistent Object with keys,” "https://github.com/OP-TEE/optee_test/pull/92", [On-line] (Accessed in May 23, 2016).

[18] M. Gentilal, “ramdisk.img size,” "https://github.com/OP-TEE/optee_os/issues/822", [Online] (Ac-cessed in June 9, 2016).

[19] ——, “ARM Juno GCC5 support note.” "https://github.com/OP-TEE/optee_os/pull/844", [Online](Accessed in June 9, 2016).

[20] L. W. Security, “GCC5 support.” "https://github.com/OP-TEE/optee_os#573-gcc5-support", [On-line] (Accessed in August 17, 2016).

[21] Linaro, “OP-TEE : Open Source Trusted Execution Environment,” "https://www.op-tee.org/,", p.2016, [Online] (Accessed in September 26, 2016).

[22] M. Gentilal, “Added a note for how to get SSH and SCP (for the juno board),” "https://github.com/OP-TEE/optee_os/pull/978", [Online] (Accessed in August 8, 2016).

[23] ——, “Dropbear,” "https://github.com/Miraje/dropbear/blob/master/README.md,", 2016, [Online](Accessed in September 28, 2016).

[24] T. Alves and D. Felton, “Trustzone: Integrated hardware and software security,” ARM white paper,vol. 3, no. 4, pp. 18–24, 2004.

[25] ARM, “ARM Compiler toolchain: Using the Assembler,” p. 204, 2011. [Online]. Available: http://infocenter.arm.com/help/topic/com.arm.doc.dui0473c/DUI0473C_using_the_arm_assembler.pdf

[26] GlobalPlatform, “GlobalPlatform: What is a TEE?” "http://www.globalplatform.org/mediaguidetee.asp#_Toc419214135", [Online] (Accessed in May 29, 2016).

[27] ——, “About GlobalPlatform,” "https://www.globalplatform.org/aboutus.asp", [Online] (Accessed inAugust 30, 2016).

[28] ——, “TEE System Architecture v1.0,” no. December, pp. 1–24, 2011. [Online]. Available:http://www.globalplatform.org/specificationsdevice.asp

[29] ——, “TEE Client API Specification v1.0,” no. July, pp. 1–58, 2010. [Online]. Available:http://www.globalplatform.org/specificationsdevice.asp

[30] Globalplatform, “TEE Internal API Specification v1.1,” no. June, pp. 1–202, 2011. [Online].Available: http://www.globalplatform.org/specificationsdevice.asp

[31] GlobalPlatform, “Trusted User Interface API v1.0,” no. June, pp. 1–48, 2013. [Online]. Available:http://www.globalplatform.org/specificationsdevice.asp

[32] ARM, “Products | TrustZone – ARM,” "https://www.arm.com/products/security-on-arm/trustzone,",[Online] (Accessed in September 26, 2016).

66

Page 83: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

[33] ——, “AMBA AXI and ACE Protocol Specification,” pp. 1–306, 2011. [Online]. Available:http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ihi0022d/index.html

[34] S. J. Murdoch, “Introduction to Trusted Execution Environments ( TEE ) – IY5606,” 2015. [Online].Available: http://sec.cs.ucl.ac.uk/users/smurdoch/talks/rhul14tee.pdf

[35] BitcoinWiki, “Double-spending - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Double-spending", 2015,[Online] (Accessed in September 4, 2016).

[36] BitcoinWiki, “Bitcoin Improvement Proposals - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Bitcoin_Improvement_Proposals", [Online] (Accessed in September 2, 2016).

[37] ——, “Protocol documentation - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Protocol_documentation",[Online] (Accessed in September 3, 2016).

[38] ——, “Proof of work - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Proof_of_work", [Online] (Accessed inSeptember 4, 2016).

[39] CoinDesk, “How do bitcoin transactions work? - CoinDesk,” "http://www.coindesk.com/information/how-do-bitcoin-transactions-work/", 2015, [Online] (Accessed in September 4, 2016).

[40] P. D. Gallagher and C. Romine, “FIPS PUB 186-4 Digital Signature Standard (DSS),” 2013, [On-line] (Accessed in September 4, 2016).

[41] J. Foti, “FIPS PUB 180-4 Secure Hash Standard (SHS),” [Online] (Accessed in September 4,2016).

[42] A. Bosselaers, “The hash function RIPEMD-160,” "https://homes.esat.kuleuven.be/~bosselae/ripemd160.html", [Online] (Accessed in September 4, 2016).

[43] BitcoinWiki, “Base58Check encoding - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Base58Check_encoding", [Online] (Accessed in September 4, 2016).

[44] Daniel R. L. Brown, “Standards for Efficient Cryptography - SEC 1: Elliptic Curve Cryptography,”p. 144, 2009. [Online]. Available: http://www.secg.org/sec1-v2.pdf

[45] ——, “Standards for Efficient Cryptography 2 (SEC 2) : Recommended Elliptic CurveDomain Parameters,” Standards for Efficient Cryptography, p. 37, 2010. [Online]. Available:http://www.secg.org/sec2-v2.pdf

[46] BitcoinWiki, “Secp256k1 - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Secp256k1", 2016, [Online] (Ac-cessed in September 4, 2016).

[47] D. Schwartz, “Why does Bitcoin use two hash functions (SHA-256 and RIPEMD-160) to createan address? - Bitcoin Stack Exchange,” "http://bitcoin.stackexchange.com/questions/9202/why-does-bitcoin-use-two-hash-functions-sha-256-and-ripemd-160-to-create-an-ad", 2013,[Online] (Accessed in September 4, 2016).

[48] BitcoinWiki, “Testnet - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Testnet", 2016, [Online] (Accessed inSeptember 4, 2016).

[49] ——, “Hashcash - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Hashcash", 2016, [Online] (Accessed inSeptember 4, 2016).

67

Page 84: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

[50] BitcoinWiki, “Technical background of version 1 Bitcoin addresses - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses", 2016, [Online] (Accessedin September 4, 2016).

[51] M. Moreno, “Bitcoin address collision,” "https://www.miguelmoreno.net/bitcoin-address-collision/",2013, [Online] (Accessed in September 4, 2016).

[52] BitcoinWiki, “Transaction - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Transaction", 2016, [Online] (Ac-cessed in September 6, 2016).

[53] CryptoCompare, “Bitcoin Transaction Inputs and Outputs?” "https://www.cryptocompare.com/mining/guides/bitcoin-transaction-inputs-and-outputs/", 2016, [Online] (Accessed in September6, 2016).

[54] Blockchain.info, “Bitcoin transaction 84c2424f...” "https://blockchain.info/tx-index/59733405/0",2014, [Online] (Accessed in September 22, 2016).

[55] ——, “Bitcoin transaction 13aaf3df...” "https://blockchain.info/tx/13aaf3df20b9ec99b5c253f9cd3c784c39275083b9fca884e0767b88419bca28", 2014, [Online](Accessed in September 22, 2016).

[56] Bitcoin.org, “Securing your wallet - Bitcoin,” "https://bitcoin.org/en/secure-your-wallet#hardwarewallet", 2016, [Online] (Accessed in September 22, 2016).

[57] BitcoinWiki, “BIP 0032 - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/BIP_0032", 2015, [Online] (Ac-cessed in September 6, 2016).

[58] ——, “Bitcoin Core - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Bitcoin_Core", 2015, [Online] (Ac-cessed in September 5, 2016).

[59] MultiBit, “The Bitcoin Wallet for Your Desktop,” "https://multibit.org/", 2016, [Online] (Accessed inSeptember 5, 2016).

[60] Electrum, “Electrum Bitcoin Wallet,” "https://electrum.org/#home", 2016, [Online] (Accessed inSeptember 5, 2016).

[61] Armory, “Best Bitcoin Wallet Armory | Multi-Signature Cold Storage,” "https://www.bitcoinarmory.com/", 2016, [Online] (Accessed in September 5, 2016).

[62] Coinbase, “Bitcoin wallet,” "https://www.coinbase.com/", 2016, [Online] (Accessed in September5, 2016).

[63] Xapo, “Xapo - Bitcoin Wallet & Vault,” "https://xapo.com/", 2016, [Online] (Accessed in September5, 2016).

[64] Blockchain.info, “The World’s Most Popular Bitcoin Wallet,” "https://blockchain.info/wallet/#/", 2016,[Online] (Accessed in September 5, 2016).

[65] Bitcoin Wallet developers, “Bitcoin Wallet Application – Google Play Store,” "https://play.google.com/store/apps/details?id=de.schildbach.wallet", 2016, [Online] (Accessed in September 5,2016).

[66] Mycelium, “Mycelium Wallet,” "https://wallet.mycelium.com/", 2016, [Online] (Accessed in Septem-ber 5, 2016).

68

Page 85: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

[67] Copay, “Copay – Secure, Shared Bitcoin Wallet,” "https://copay.io/", 2016, [Online] (Accessed inSeptember 5, 2016).

[68] Ledger, “Ledger Wallet - Ledger Nano - Secure and smart Bitcoin hardware wallet,” "https://www.ledgerwallet.com/products/1-ledger-nano", 2016, [Online] (Accessed in September 5, 2016).

[69] KeepKey, “KeepKey: A Simple Bitcoin Hardware Wallet,” "https://www.keepkey.com/", 2016, [On-line] (Accessed in September 5, 2016).

[70] TREZOR, “TREZOR: The Bitcoin Safe,” "https://bitcointrezor.com/", 2016, [Online] (Accessed inSeptember 5, 2016).

[71] Butterfly Labs, “Bitcoin Wallet Hardware | Butterfly Labs,” "http://www.butterflylabs.com/bitcoin-hardware-wallet/", 2016, [Online] (Accessed in September 5, 2016).

[72] BitcoinWiki, “Address - Bitcoin Wiki,” "https://en.bitcoin.it/wiki/Address", 2016, [Online] (Accessedin September 6, 2016).

[73] M. Pirker and D. Slamanig, “A framework for privacy-preserving mobile payment on security en-hanced ARM trustzone platforms,” Proc. of the 11th IEEE Int. Conference on Trust, Security andPrivacy in Computing and Communications, TrustCom-2012 - 11th IEEE Int. Conference on Ubiq-uitous Computing and Communications, IUCC-2012, pp. 1155–1160, 2012, doi: 10.1109/Trust-Com.2012.28.

[74] W. H. W. Hussin, P. Coulton, and R. Edwards, “Mobile ticketing system employing TrustZonetechnology,” Mobile Business, 2005. ICMB 2005. International Conference on, pp. 651–654,2005, doi: 10.1109/ICMB.2005.71. [Online]. Available: 10.1109/ICMB.2005.71

[75] Trustonic, “Rivetz Teams with Trustonic to Secure Mobile Bitcoin Wallets,” " https://www.trustonic.com/news-events/pr/rivetz-trustonic-bitcoin-wallets", July 2014, [Online] (Accessed in August 21,2016).

[76] J. Young, “Ledger Transforms Smartphones into Hardware Wallets,” " https://cointelegraph.com/news/ledger-transforms-smartphones-into-hardware-wallets", March 2016, [Online] (Accessed inAugust 21, 2016).

[77] Rivetz, “About the Rivetz Team,” "https://rivetz.com/index.php/team,", 2016, [Online] (Accessed inSeptember 8, 2016).

[78] ——, “Rivetz Preview Program,” " https://rivetz.com/docs/getstarted.html#Rivetz_Preview_Program", [Online] (Accessed in August 31, 2016).

[79] Ledger, “Ledger - Secure Blockchain Platform - Hardware Wallets for Consumers - HSM for Enter-prises - Blockchain for IoT,” "http://www.ledger.co/#about,", 20116, [Online] (Accessed in Septem-ber 8, 2016).

[80] ——, “Ledger Trustlet – Aplicações Android no Google Play,” "https://play.google.com/store/apps/details?id=com.ledger.wallet.bootstrap,", 2016, [Online] (Accessed in September 8, 2016).

[81] ——, “Ledger BOLOS-TEE SDK,” "https://github.com/LedgerHQ/bolos-tee,", 2016, [Online] (Ac-cessed in September 8, 2016).

[82] Trustonic, “About us | Trustonic,” "https://www.trustonic.com/about-trustonic,", 2016, [Online] (Ac-cessed in September 8, 2016).

69

Page 86: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

[83] D. Fisher, “Huge Number of Android Phones Vulnerable to Crit-ical TrustZone Bug | On the Wire,” "https://www.onthewire.io/huge-number-of-android-phones-vulnerable-to-critical-trustzone-bug/,", 2016, [Online] (Ac-cessed in September 8, 2016).

[84] Allten, “[ANN] BitSafe Hardware Wallet Now Shipping,” "https://bitcointalk.org/index.php?topic=152517.0,", 2013, [Online] (Accessed in September 8, 2016).

[85] Someone42, “Hardware Bitcoin wallet - a minimal Bitcoin wallet for embedded devices - BitSafev1,” "https://bitcointalk.org/index.php?topic=78614.0,", 2012, [Online] (Accessed in September 8,2016).

[86] ——, “Hardware Bitcoin wallet - a minimal Bitcoin wallet for embedded devices - BitSafe v2,”"https://bitcointalk.org/index.php?topic=78614.msg1327630#msg1327630,", 2012, [Online] (Ac-cessed in September 8, 2016).

[87] ——, “Hardware Bitcoin wallet - a minimal Bitcoin wallet for embedded devices - BitSafe v3,”"https://bitcointalk.org/index.php?topic=78614.msg1829506#msg1829506,", 2013, [Online] (Ac-cessed in September 8, 2016).

[88] TREZOR, “Trezor’s GitHub Page,” "https://github.com/trezor,", [Online] (Accessed in September15, 2016).

[89] Free Software Foundation, “GNU Lesser General Public License v3.0 - Choose a License,” "http://choosealicense.com/licenses/lgpl-3.0/,", 2007, [Online] (Accessed in September 15, 2016).

[90] KeepKey, “KeepKey’s GitHub Page,” "https://github.com/keepkey/,", [Online] (Accessed in Septem-ber 15, 2016).

[91] Certification body of the BSI in the context of the certification scheme, “Evaluation Methodologyfor CC Assurance Classes for EAL5+ (CC v2.3 & v3.1) and EAL6 (CC v3.1),” p. 139, 2009, [Online](Accessed in September 15, 2016).

[92] “BSD 2-clause “Simplified” License - Choose a License,” "http://choosealicense.com/licenses/bsd-2-clause/,", [Online] (Accessed in September 15, 2016).

[93] S. Sadasivan, “An Introduction to the ARM Cortex-M3 Processor,” White Paper, 2006.[Online]. Available: https://web.archive.org/web/20140726212528/http://www.arm.com/files/pdf/IntroToCortex-M3.pdf

[94] Someone42, “bitsafe-example-wallet,” "https://github.com/someone42/bitsafe-example-wallet,",2014, [Online] (Accessed in September 27, 2016).

[95] Microchip, “32-Bit MCUs | Microchip Technology Inc.” "https://www.microchip.com/design-centers/32-bit,", 2016, [Online] (Accessed in September 20, 2016).

[96] NXP, “ARM mbed LPC11U24 Board | NXP,” "http://www.nxp.com/products/microcontrollers-and-processors/arm-processors/lpc-cortex-m-mcus/lpc-cortex-m0-plus-m0/lpc1100-cortex-m0-plus-m0/arm-mbed-lpc11u24-board:OM13032,", 2016, [Online] (Accessed inSeptember 20, 2016).

[97] MikroElektronika, “MINI-AT - AVR USB development board in DIP26 form factor,” "http://www.mikroe.com/mini/at/,", 2016, [Online] (Accessed in September 20, 2016).

70

Page 87: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

[98] HardwareWallets.com, “Hardware Wallets - BitSafe v4,” "http://www.hardwarewallets.com/,", [On-line] (Accessed in September 8, 2016).

[99] IEEE 1619 Security in Storage Working Group and others, “IEEE Standard for CryptographicProtection of Data on Block-Oriented Storage Devices,” IEEE Std 1619-2007, no. April, pp. c1–32,2008, doi: 10.1109/IEEESTD.2008.4493450.

[100] Morgan, “Announcing Our Worst Passwords of 2015 | TeamsID,” "https://www.teamsid.com/worst-passwords-2015/,", 2016, [Online] (Accessed in September 28, 2016).

[101] Wikepedia, “List of ARM microarchitectures,” "https://en.wikipedia.org/wiki/List_of_ARM_microarchitectures,", [Online] (Accessed in September 28, 2016).

[102] ARM, “Processors | Cortex-A – ARM,” "http://www.arm.com/products/processors/cortex-a,", [On-line] (Accessed in September 28, 2016).

[103] R. Smith, “ARM Announces ARMv8-M Instruction Set For Microcontrollers – TrustZone Comesto Cortex-M,” "http://www.anandtech.com/show/9775/arm-announces-armv8m-instruction-set,",2015, [Online] (Accessed in September 28, 2016).

[104] ZedBoard.org, “ZedBoard Technical Specifications,” "http://zedboard.org/content/zedboard-0,",[Online] (Accessed in September 25, 2016).

[105] 96Boards, “Documentation - 96Boards Hikey Quickstart,” "http://www.96boards.org/documentation/ConsumerEdition/HiKey/Quickstart/README.md/,", [Online] (Accessed inSeptember 25, 2016).

[106] NXP, “i.MX53 Quick Start Board | NXP,” "http://www.nxp.com/products/power-management/pmics/pmics-for-i.mx-processors/i.mx53-quick-start-board:IMX53QSB,", [Online] (Accessed in Septem-ber 25, 2016).

[107] ARM, “Juno ARM Development Platform - ARM,” "http://www.arm.com/products/tools/development-boards/versatile-express/juno-arm-development-platform.php,", [Online] (Accessedin September 25, 2016).

[108] ——, “ARM Architecture Reference Manual: ARMv7-A and ARMv7-R edition,” p. 2736, 2014.

[109] ——, “big.LITTLE Technology: The Future of Mobile,” ARM white paper, p. 12, 2013. [Online].Available: https://www.arm.com/files/pdf/big_LITTLE_Technology_the_Futue_of_Mobile.pdf

[110] ——, “ARM Discloses Technical Details Of The Next Ver-sion Of The ARM Architecture,” "http://www.arm.com/about/newsroom/arm-discloses-technical-details-of-the-next-version-of-the-arm-architecture.php,", 2011, [Online](Accessed in September 26, 2016).

[111] L. W. Security, “OP-TEE Test,” "https://github.com/OP-TEE/optee_test,", 2016, [Online] (Accessedin September 28, 2016).

[112] Linaro, “HKG15-311: OP-TEE for Beginners and Porting Review,” "http://pt.slideshare.net/linaroorg/hkg15311-optee-for-beginners-and-porting-review,", 2015, [Online] (Accessed inSeptember 27, 2016).

[113] L. W. Security, “Secure Storage In OP-TEE,” "https://github.com/OP-TEE/optee_os/blob/master/documentation/secure_storage.md,", 2016, [Online] (Accessed in September 28, 2016).

71

Page 88: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

[114] ARM, “Juno ARM Development Platform: Getting Started Guide v1.0,” p. 30, 2015.[Online]. Available: http://infocenter.arm.com/help/topic/com.arm.doc.dui0928e/DUI0928E_juno_arm_development_platform_gsg.pdf

[115] Ash Wilding, “Using Linaro’s deliverables on Juno | ARM Connected Community,” "https://community.arm.com/docs/DOC-10804,", 2016, [Online] (Accessed in September 28, 2016).

[116] ——, “FAQ: What are the differences between the Linar... | ARM Connected Community,” "https://community.arm.com/docs/DOC-10482,", 2015, [Online] (Accessed in September 28, 2016).

[117] ARM, “ARM Trusted Firmware,” "https://github.com/jenswi-linaro/arm-trusted-firmware,", [Online](Accessed in September 28, 2016).

[118] L. W. Security, “OP-TEE: ARM Juno Board setup,” "https://github.com/OP-TEE/optee_os/blob/401cc1ea71607d7c9f7c01046a27adbce62de575/README.md#43-arm-juno-board,", 2016, [On-line] (Accessed in September 28, 2016).

[119] Linaro, “Linaro Snapshot 16.01,” "http://snapshots.linaro.org/member-builds/armlt-platforms-release/18/,", 2016, [Online] (Accessed in September 28, 2016).

[120] L. W. Security, “OP-TEE - version 2.0.0,” "https://github.com/OP-TEE/optee_os/blob/master/CHANGELOG.md#op-tee---version-200,", 2016, [Online] (Accessed in September 28, 2016).

[121] M. Gentilal, “Juno: failed to find an OP-TEE supplicant device,” "https://github.com/OP-TEE/optee_os/issues/735,", 2016, [Online] (Accessed in September 28, 2016).

[122] Matt Johnston, “Dropbear SSH,” "https://matt.ucc.asn.au/dropbear/dropbear.html,", [Online] (Ac-cessed in September 28, 2016).

[123] Acme Systems, “Building BuildRoot 2016.02,” "http://www.acmesystems.it/buildroot_2016_02,",[Online] (Accessed in September 28, 2016).

[124] L. W. Security, “Tui drivers,” "https://github.com/OP-TEE/optee_os/pull/898,", 2016, [Online] (Ac-cessed in September 28, 2016).

[125] M. Gentilal, “TEE_Malloc() and TEE_GenerateRandom(),” "https://github.com/OP-TEE/optee_os/issues/923,", 2016, [Online] (Accessed in September 28, 2016).

[126] N. Ferguson and B. Schneier, Wiley New York. Wiley, 2003, vol. 23, isbn: 047122894X.

[127] M. Gentilal, “TrustZone Backed Bitcoin Wallet Source Code,” "http://web.tecnico.ulisboa.pt/ist173547/TrustZone-Backed-Bitcoin-Wallet.zip,", 2016, password: m!r@j&D!ss&rt@tion2016,[Online] (Accessed in September 28, 2016).

[128] ——, “Example Trusted Application Protocol,” "https://github.com/Miraje/Example-Trusted-Application-Protocol,", 2016, [Online] (Accessed in September 28, 2016).

[129] L. W. Security, “Q4.11: Introduction to eMMC,” "http://pt.slideshare.net/linaroorg/intro-to-emmc,",[Online] (Accessed in September 28, 2016).

[130] Haleyyew, “Microbenchmark measurement,” "https://github.com/OP-TEE/optee_os/issues/1040#issuecomment-245967318,", 2016, [Online] (Accessed in September 28, 2016).

[131] GlobalPlatform, “GlobalPlatform Specifications,” "http://www.globalplatform.org/specificationsdevice.asp", [Online] (Accessed in August 30, 2016).

72

Page 89: TrustZone-backed Bitcoin Wallet - ULisboa · of Bitcoin, since it is a decentralized digital currency this means that there is not any institution, bank, authority or government that

[132] ARM, “Group: ARM Development Platforms | ARM Connected Community,” "https://community.arm.com/groups/arm-development-platforms,", 2016, [Online] (Accessed in September 25, 2016).

[133] ——, “ARM Architecture Reference Manual: ARMv8, for ARMv8-A architecture profile - Beta,”p. 5158, 2013. [Online]. Available: http://115.28.165.193/down/arm/arch/ARMv8-A_Architecture_Reference_Manual_(Issue_A.a).pdf

[134] Linaro, “WorkingGroups/Security/OP-TEE - Linaro Wiki,” "https://wiki.linaro.org/WorkingGroups/Security/OP-TEE,", 2016, [Online] (Accessed in September 26, 2016).

[135] Flottetotte, “Best practice to include library into TA?” "https://github.com/OP-TEE/optee_os/issues/1003,", 2016, [Online] (Accessed in September 28, 2016).

[136] Hagai Bar-El, “Introduction to Side Channel Attacks,” [Online] (Accessed in September 28, 2016).

73