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

Acknowledgments

I 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 during the process of developing this dissertation. To Paulo Martins for his helpful advices, suggestions, critical comments, and for his unconditional support 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 develop this 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 ii Resumo

Nos ú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. Enquanto que a chave pública é utilizada como endereço destino de um pagamento, a chave privada é usada para aceder aos fundos armazenados no endereço correspondente, através da assinatura digital de transações. A maioria das carteiras de Bitcoin processam a informação sensível num ambiente susceptível a ataques. Além disso, a segurança que é atribuída ao armazenamento dessa informação é suportada na sua encriptação com uma chave baseada na palavra-passe do utilizador, tornando-se suscetível a ataques de dicionário. Como a chave privada define a posse dos bitcoins, deve ser muito bem protegida e guardada, criando assim a necessidade de se utilizar medidas de segurança mais robustas do que as 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 Bitcoins flexível, confiável e resistente a ataques de dicionário e de canal lateral. A utilização desta extensão tem 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; Carteira de Hardware; Mundo Seguro; TrustZone.

iii iv Abstract

The 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 used as an address for a payment, the private key is used to access the funds stored in the correspondent address, through the digital signature of transactions. Sensitive information is processed in an environment susceptible to attacks in almost every Bitcoin wallet. Moreover, the security that is provided to store such information, is supported on the encryption with a key based in a user’s password, making it susceptible to dictionary attacks. As the private key defines the ownership of bitcoins, it must be very well protected and secured. Thus, the need of using stronger security measures than the ones that are currently used arises. ARM has made available an extension of processors architectures, designated TrustZone, which allows for the separation of trusted and non-trusted environments, while ensuring the integrity of the Operating System code. In this dissertation, it is proposed the exploitation of TrustZone, in order to implement a flexible and reliable Bitcoin wallet that is more resilient to dictionary and side-channel attacks. Making use this extension comes with the downside that writing and reading operations become slower, due to the encrypted storage, but it is shown that cryptographic operations can in fact be executed more efficiently as 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 vi Contents

Acknowledgments ...... i Resumo ...... iii Abstract ...... v List of Tables ...... ix List of Figures ...... xi Acronyms ...... xiii

1 Introduction 1 1.1 Motivation ...... 2 1.2 Objectives ...... 3 1.3 Main Contributions ...... 4 1.4 Outline ...... 5

2 Background 7 2.1 TrustZone Technology ...... 8 2.1.1 Overview ...... 8 2.1.2 Hardware Architecture ...... 9 2.1.3 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

3 Proposed TrustZone-based Bitcoin Wallet 23 3.1 Available Base Wallets ...... 24 3.2 Base Wallet Description ...... 28 3.3 Proposed Improvements ...... 33 3.4 Summary ...... 40

4 Implementation Details and System Assessment 43 4.1 TrustZone-enabled Platform ...... 44 4.2 Software Stack ...... 46 4.3 Implementation ...... 48

vii 4.3.1 Platform Configuration ...... 48 4.3.2 Implementation Details ...... 53 4.4 Experimental Results ...... 55 4.5 Summary ...... 59

5 Conclusion 61 5.1 Summary and Overall Conclusions ...... 62 5.2 Future Work ...... 63

Bibliography 65

viii List of Tables

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

3.1 Main Hardware Wallets...... 25 3.2 BitSafe’s development prototype main characteristics [87]...... 27 3.3 Brief description of the main Wallet Functions [11]...... 31 3.4 Brief description of the main Transaction Functions [11]...... 31 3.5 Brief description of the main Pseudo-Random Number Generation Functions [11]. . . . . 32 3.6 Brief description of the platform dependent functions [11]...... 32 3.7 Available packets for the communication between BitSafe and the host [11]...... 33

4.1 Processors with TrustZone support. [101, 102] ...... 44 4.2 Main characteristics of TrustZone-enabled development boards...... 45 4.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 is presented...... 56 4.4 Execution time of the used Cryptographic Operations. The values are presented in clock cycles. In parenthesis the execution time increase in percentage of the TBW relative to the OBW is presented...... 57 4.5 Execution time of the available packets. The values are presented in clock cycles. In parenthesis the execution time increase in percentage of the TBW relative to the OBW is presented...... 58 4.6 Qualitative comparison between the OBW and the TBW...... 59

ix x 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]...... 9 2.2 Simplified structure and flow of the Bitcoin architecture...... 13 2.3 Example of a fork in the blockchain...... 14 2.4 Simplified Bitcoin transaction example...... 17 2.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 the information stored in each wallet. The represented memory is byte addressable...... 28 3.2 The three main modules of the BitSafe wallet...... 30 3.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 implemented in 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 the boxes they are contained...... 40

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

xi xii Acronyms

AES Advanced Encryption Standard AMBA Advanced Microcontroller Bus Architecture API Application Programming Interface ARM Advanced RISC Machine AXI Advanced eXtensible Interface BIP Bitcoin Improvement Proposal CA Client Application CPU Central Processing Unit DRBG Deterministic Random Bit Generator DRM Digital Rights Management ECC Elliptic Curve Cryptography ECDSA Elliptic Curve Digital Signature Algorithm GCC GNU Compiler Collection HD Hierarchical Deterministic HMAC Hash-based Message Authentication Code IP Intellectual Property OBW Original Base Wallet OEM Original Equipment Manufacturer OP-TEE Open Source Trusted Execution Enviornment OS Operating System P2PKH Pay To Public Key Hash PBKDF2 Password-Based Key Derivation Function 2 REE Rich Execution Environment RIPEMD RACE Integrity Primitives Evaluation Message Digest SCP Secure Copy SDK Software Development Kit SHA Secure Hash Algorithm SMC Secure Monitor Call SoC System on Chip SSH Secure Shell TA Trusted Application TBW TrustZone-backed Bitcoin Wallet TEE Trusted Execution Environment

xiii xiv CHAPTER 1

INTRODUCTION

Contents 1.1 Motivation ...... 2 1.2 Objectives ...... 3 1.3 Main Contributions ...... 4 1.4 Outline ...... 5

1 In the last few years, the Internet availability has been increasing at a steady pace, and at the end of June 2016 it was used by almost half (49.2%) of the world’s population [1]. This widespread use made 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]. There are 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 in November 2008 under the pseudonymous Satoshi Nakamoto who described it as an “electronic payment system based on cryptographic proof instead of trust, allowing any two willing parties to transact directly with each other without the need for a trusted third party” [3]. The Bitcoin protocol is considered to be the first one of its kind, it uses a peer-to-peer network to generate and exchange digital currency as well as to verify all the performed transactions [4, 5]. This characteristic could be considered the most important of 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 stronger protection against frauds [6]. Every transaction makes use of public key cryptography, viz., to make transactions 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 defines the 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 system architectures to increase their security [7]. It enables a logical separation between a secure and a non-secure environment, and when combined with a well designed system and secure software it can ensure that sensitive data remains safe, no matter what the non-secure environment does [7]. These technological characteristics make it very attractive for payment services, authentication processes, and to handle confidential information in a secure manner. A recent example is the Knox platform announced by Samsung® in 2013, which uses the TrustZone technology to perform security services, 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 grown drastically as well as the number of transactions performed each day (Figure 1.2). A recent proof of this fact is that, in the last years, many Venezuelan citizens started to abandon the bolivar and began to adopt this virtual currency as an escape hatch for the inflation and strict capital controls, which lead in the first week of August 2016 to a new record of Bitcoin trading volume that reached 141,744,733 bolivars (about $141,000 USD) [10]. With the increasing trust that is deposited on Bitcoin, the need of using stronger security measures than the ones that are currently used arises. For example, using a user’s password, which can be easily guessed, 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 the private key is quite safer. While sensitive data can be stored or transmitted in a protected form, its processing is usually done in the clear, which means that it can easily be exposed to an attacker and

2 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 storage and the process of signing each transaction.

$1,000,000,000.00 $100,000,000.00 $10,000,000.00 $1,000,000.00 $100,000.00 $10,000.00 xchanged per day per xchanged $1,000.00 $100.00 Amout e Amout $10.00 $1.00 Jan-09 Jan-10 Jan-11 Jan-12 Jan-13 Jan-14 Jan-15 Jan-16 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].

1000000

100000

10000

actions per dayper actions 1000

100

10 Number of transof Number 1 Jan-09 Jan-10 Jan-11 Jan-12 Jan-13 Jan-14 Jan-15 Jan-16 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 security features associated with this technology. Then, the Bitcoin protocol and the different types of Bitcoin wallets that are available will be analyzed, in order to find the one that is more prone to benefit from the high 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 assessed the 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 Furthermore, it is intended to develop a Bitcoin wallet that is efficient and platform-independent so it 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 of supporting 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 this way, it is created a more transparent solution that can be verified, customized, and improved by anyone with associated low costs.

1.3 Main Contributions

With the TrustZone-based Bitcoin wallet developed and presented in this dissertation it is shown that it is 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 to the OP-TEE project, namely:

• The OP-TEE supported several platforms including the ARM Juno board, however, this support was 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 modifications had to be applied to the available software to add that possibility. The performed changes were reported and integrated into the OP-TEE project [15] so it could support the ARM Juno-r2 board natively;

• While developing an application that would run on the TrustZone, some features were detected to be 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 the OP-TEE developers it was suggested a test case to detect this problem. Later, this test case was integrated into the OP-TEE test suite case [17];

• As part of the OP-TEE development process, the complier that was used was upgraded to the GNU Compiler Collection (GCC) 5, and that change required a copy of quite a few more files than before to the root file system. As a consequence, there was an increase of the RAM disk image 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 size limitation, the addresses that defined where the images were loaded into the Juno’s flash memory were modified and rearranged. Then, the changed addresses were shared with the OP-TEE developers [19] and now 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].

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

4 support of Secure Shell (SSH) and Secure Copy (SCP) to the current setup. This information was also 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 that were made are provided in Chapter 4. In the developed work, a detailed analysis was made of how to make an existing Bitcoin wallet safer by examining which components should be transfered to the TrustZone’s secure environment. Although this analysis is applied to a Bitcoin wallet, it could easily be extended to other applications making this dissertation an open work. Up until now, there was not any work in the existing literature that presented experimental results about the execution of the transferred functions to the TrustZone. In this dissertation is evaluated the impact on the performance of the modules that were transferred to the TrustZone, and provided 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 wallet can 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 also be scrutinized by the scientific community in order to further improve its safety, and at the same time it can be adapted and integrated in other products by any manufacturer or developer as a way to add more functionality. As one of the last contributions, the Bitcoin wallet proposed in this dissertation was described in a publication 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 19th Annual 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 overview about the TrustZone, where the impacts that the hardware architecture has on the infrastructure where this technology is applied are explained. Possible software architectures that can exploit this security extension are also presented. Furthermore, the security features that are available with the use of TrustZone 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 wallets that are available. Then, an analysis about the security features associated with the use of this digital currency 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 having determined the main modules of this wallet, they are evaluated in terms of their security, and proposals are 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 followed to configure the TrustZone-enabled platform with all the required software is described. It should be noted that this process was not trivial, since several elements were lacking for the correct exploitation of the TrustZone. Then, the modifications to the chosen wallet to integrate the new selected features are presented. Finally, the results obtained for the executions times before and after applying the proposed modifications are presented and analyzed. The security features of the proposed wallet will also be

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

6 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 An increasing concern over the security of the implementations of cryptographic protocols has led ARM to release an hardware-backed technology to enhance the integrity and confidentiality of these implementations. 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 integrated in the ARM architecture. The interconnections enabled by the TrustZone between the software and the hardware will be presented from an architectural point of view. It is also highlighted the security features derived 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 are presented. Some of the most sensitive operations like Bitcoin address generation and the transaction process are carefully discussed. Bitcoin wallets are also presented as they are responsible for handling the aforementioned operations. The security features of Bitcoin are also referred. Afterwards, related work 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 its architecture, which is widely deployed specially among smart devices platforms. This technology takes advantage of the internal hardware that is located within the System on Chip (SoC) along with software components to create a secure and trusted environment where confidentiality and integrity of almost any asset can be guaranteed [7, 24]. In this way, a flexible framework is provided that semiconductor and Original Equipment Manufacturer (OEM) developers can use it in order to implement their own security features with minimal impact on power consumption, performance and area, which otherwise would be much 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 one hand, there is the Secure World, that is responsible for the security subsystem and, consequently, for the execution of trusted software, accessing sensitive hardware and processing critical data. Thus, it is possible to have applications that can access secure memory space and peripherals with the guarantee that the provided data was not tampered with and is trustworthy [7]. These applications are only executed in 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 the Normal 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 are usually 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 to this mode is strictly controlled when made by the Normal World, which is only possible through explicit Secure Monitor Calls (SMCs), interrupt exceptions, or external abort exceptions. For the Secure World this entry is a little more flexible, and can be achieved by directly writing to Current Program Status Register [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 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 associated with the development and integration of the TAs. GlobalPlatform [27] is an industry association that has been responsible for driving TEE standardization by presenting some guidelines like the TEE Systems Architecture [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] that defines the communication between CAs and TAs; TEE Internal Core API Specification [30] that is used by the TAs to perform general security functions; and Trusted User Interface API Specification [31] that allows 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 accordance with TEE Systems Architecture, and which had an Trusted OS that offered to the TAs, at least, the TEE Internal Core API, and if possible the Trusted User Interface API. In turn, the TAs should use, whenever it is possible, the previous mentioned APIs to perform their operations, and should communicate with the CAs through well defined entry-point calls using the TEE Client API. Following this methodology, it is 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 simplified design of the previously mentioned scenario.

Common Execution Environment TEE

Trusted Trusted Generic Security CA with TA Security Application Application Application Client support Service 1 2 User space User space

TEE Client API TEE Internal Core API

Rich OS Secure Trusted OS Storage Monitor

Trusted User Interface API Privileged space Privileged space

Secure Hardware Resources (crypto, timers, watchdog, screens, keyboard, ...) ARM TrustZone-enabled Chipset

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 running the two virtual worlds in a time-slice fashion [7], each one with a different vision of the SoC’s hardware and software resources to ensure that none of the Secure World protected resources are accessible outside 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 fabric guaranties that there is not any violation on the access of the hardware and software designated as secure [7]. Therefore, the available memory can be split in secure and non-secure regions, and while the 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. The access 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 where the monitor mode is executed. When the Secure Monitor receives the instruction to switch world, it stores the currently running context and loads the previously stored one for the world for which is changing to. It is important to notice that on monitor mode the processor is always executing the Secure World regardless of the world that requested the switch, in order that the context information is stored in secure memory regions preventing it from being compromised . An important part of the TrustZone hardware architecture is the debug solution provided. There are two 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 configurations available: 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 debug allows to observe but not modify or control resources of the system. While the user debug mode is designated 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 only be 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 of developing a TEE. However, as the TrustZone is an open architecture, there is not a predefined software stack that should be used. Instead, any developer can implement their own version of the software environment to fit their needs. For example, instead of using the same core for the two virtual worlds as described, it is possible to have a dedicated processor just for the Secure World [7]. The software architecture for the TEE can also be simpler than indicated before. Instead of having a full dedicated Trusted 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 implementation should take into account, more specifically, the software developed for the Secure World should be as minimal as possible to reduce the surface of attack and to occupy the least memory possible since it is a critical resource for some platforms; and, if a Trusted OS is implemented, it should provide a Secure Boot, which adds cryptographic checks to each step of the boot process to guarantee the integrity of the 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 it is possible to have multiple independent TAs that don’t depend on the Normal World environment, and it also allows to have different memory spaces for each TA preventing any possible tampering among secure tasks [7]. For a better understating of how a CA could use a TA for the execution of a security service, take as an example the Software Architecture presented in the Figure 2.1. When a security client that runs on 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 the arguments of the operation, then it invokes another command through the same API to indicate the desired 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 execution context of the Normal World and restores the previously stored context of the Secure World. When this is 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. After the security service preforms the operation, the obtained result is written back in the memory region indicated by the CA and where previously were the function arguments. The transaction to the Normal World 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 the previous subsections, namely, the possibility to: hide the access of critical peripherals from the Normal World; have a secure storage that is only accessible through the Secure World; perform cryptographic operations and security services in a trusted manner by using TAs; mark certain regions of memory and cache memories as secure to guarantee that the data processed in the TEE is not accessible to non-trusted components; provide each TA with its own memory space that cannot be accessed by other TAs or CAs; add integrity checks of the secure world software stack to avoid data tampering; provide a 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 breaches once the device is in production” [24]. With all these security features, it is possible to conclude that the attacks performed with the intent of tampering the TEE are impractical, as they imply a serious hardware investment [34]. In the same way, boot attacks do not work either due the use of Secure Boot, and attempts to update the firmware will also be unsuccessful if they are not properly authenticated. The assets are also protected from the most common software attacks, as all the sensitive data and security tasks are processed in the Secure World. However, there should always be given special attention to which applications are installed in the Normal 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 from untrustworthy code [34]. The lab attacks, in which the attacker has access to sophisticated laboratory equipment, are not considered in the protection provided by the TrustZone technology. Nevertheless, the TrustZone technology could be used in conjunction with the ARM SecurCore®, which is an architecture designed primarily for tamper-resistant smart cards that increases the security against physical attacks of the processor that implements that architecture [7]. From an economical point of view, ARM TrustZone technology is a relatively low cost solution when compared with dedicated secure cryptological processors, as it allows a programmable environment instead of a unique solution. It also provides protection when the data is being processed instead of just providing the cryptographic functions. Moreover, if the Secure World runs on the main processor instead of a secondary one, the TEE code will run faster and less silicon space will be used which will reduce the final cost of the product. One could also compare TrustZone with smart-cards, which are often used due the strong security they can offer. Although this security can be considered better than the one provided by TrustZone, as smart-cards lack platform binding, that is, they do not include all the necessary hardware to operate independently, they require additional specialized hardware to be used. This condition makes some applications infeasible to support [34].

11 Overall, the financial impact of a TrustZone-based solution is low in terms of the added hardware and software, but the provided level of security is very large, given the adopted design choices are correctly adapted 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, and how 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 protocol because Bitcoin relies on a peer-to-peer network, and as such the protocol ends up being defined by the group of nodes that have more computing power. Thus, whenever it is desired to improve Bitcoin features 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, since both propose possible modifications within the community to attain improvements. The main difference between 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 describes the behavior of the original Bitcoin client developed by Satoshi Nakamoto [37]. From this point on, for a better understanding, the capitalized “Bitcoin” term will be used to refer to the protocol and general concept, 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, at least, one pair of cryptographic keys, where the private key is used to sign transactions and to access the funds stored in the Bitcoin address, which is essentially the correspondent public key. As a visual example 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 user makes is signed with the private key, it is created a digital signature that is used alongside with the public 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 a transaction pool, and after a certain period of time, some nodes of the network start to aggregate those transactions into groups called transaction blocks. These nodes, also known as miners, usually verify the 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 different value. If this hash is lower or equal than a predefined 256-bit number1, then the condition for the block to 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 the final solution creating, in this way, a proof-of-work. Every 2016 valid blocks, the network checks how much time the miners took to process each block. The expected time is 10 minutes, and if the blocks have 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, they receive 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 only one coinbase transaction that is added by the network to reward the block miner and to create the digital currency. This is how the bitcoins are generated and used as a motivator for the nodes to process transactions. In addition to the reward, the miners also receive any fees associated with every transaction of the transaction block they processed. In Figure 2.2 it is pictured a simplified diagram of the previous mentioned concepts and how they interact.

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 processed blocks. This chain is denominated as blockchain and can be considered as a public ledger that records every transaction of bitcoins that was ever made in chronological order. The ledger is stored in every computer node that supports the system creating, in this way, a decentralized structure that maintains the ledger: a transaction block after being verified and processed by a miner is broadcasted to the whole network; the first receiving nodes perform some checks and then add the block to their own copy of the ledger and pass along the transaction block to other nodes which will follow the same procedure. The node’s process of checking the received transaction block is the reason why the miners verify the validity of each transaction that they include in a transaction block. If there is an invalid transaction, the nodes will ignore the block making all effort of the miner useless. Moreover, the miner would also not receive any reward or fee, because the ignored block would not be included in the blockchain so it is the same as it was never processed. Some times it happens that two transaction blocks are mined at the same time. The nodes place each block in a separate branch of their copy of the blockchain, which makes it to temporarily have an additional path. However, due network delays, the nodes receive one of the two transaction blocks first and it is after the first received block that they continue to add new transaction blocks, increasing that associated path. The network nodes always accept the longest path of the blockchain as the correct one, discarding the blocks of the smaller path. This means that the transactions that were on the blocks of 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 wait for a few transaction blocks to be processed and added to the blockchain to have the guarantee that the 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 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 and linked to the Block 73. Then, Block 76 is mined and broadcast to the Bitcoin network until eventually reaching the node. Once the block is there, and supposing that it extends the path associated with Block 75, 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 were in Block 74 are discarded and placed back in the transaction pool.

Block 75 Block 76 Proof of work: Proof of work: 000000000000000002112... 000000000000000008732... Previous block: Previous block: 000000000000000005721... 000000000000000002112...

Transaction Transaction ID = ee8b1... ID = bebc5... Block 72 Block 73 . . . . Proof of work: Proof of work: . . 000000000000000002869... 000000000000000005721... Previous block: Previous block: Transaction Transaction 000000000000000003875... 000000000000000002869... ID = cbe0a... ID = w8mu...

Transaction Transaction ID = a7k9b... ID = 73aa2...... Block 74 Proof of work: Transaction Transaction 00000000000000000d955... ID = bc6fc... ID = f840f... Previous block: 000000000000000005721...

Transaction ID = 02201......

Transaction ID = c3cef... 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 really understand what bitcoin is. Until now, bitcoins were referred to as the digital currency of Bitcoin, and in 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 balance associated with a specific Bitcoin address just by counting the bitcoins that there are there because they simply do not exist. To verify if a user has enough balance to perform a transaction it is needed to go through the transactions that have the user’s Bitcoin address as the sender or as the receiver, and verify the 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 the transaction blocks are introduced in the chain as they are processed and each of them contain the hash of the preceding block, it is created a chronological order of transactions that together contain a large amount of work, and as long as the majority of the computational power is not controlled by cooperating nodes that intend to attack the network, the double-spending problem is avoided without the need of a third 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 some bitcoins he just needs to know the destination Bitcoin address. However, there are a few differences and

14 one of them is in the way that Bitcoin addresses are generated which is custom designed and does not have 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 Base58Check encoding [43].

Previously, it was mentioned that a bitcoin address is based on a public key from a cryptographic key pair: here is where the ECDSA takes place as it is used to generate the public key. ECDSA, as the name indicates, is a variant of the Digital Signature Algorithm (DSA) [40] which uses Elliptic Curve Cryptography (ECC) [44] to generate cryptographic key pairs, sign messages, and verify the signatures of 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 specified curve, 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 which indicates 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 bytes long. At this moment, there are 65 or 33 bytes to represent a Bitcoin address but the ideal should be to have, at most, 20 bytes which would be attainable using the RIPEMD with 160 bits. However, due to unexpected interactions between RIPEMD and ECDSA a weakness might be created [47]. To mitigate this 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 for which 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 an incorrect addresses by mistake. To avoid those situations a 4 byte long checksum is used that results from the truncated double-SHA with 256 bits of the network identifier byte concatenated with the key hash. The reason why two iterations of the SHA with 256 bits are used instead of one lies in the fact that the algorithm’s design is similar to the SHA1 for which the resistance against birthday attacks has been partially broken [49]. At the moment, the SHA with 256 bits is not susceptible to such attacks but performing a double hash hardens its resistance, making this, in fact, a measure against future cryptanalytic developments [49].

The process to generate a Bitcoin address is almost complete, and the only thing that remains to discuss is the representation of the final 25 bytes (1 byte of the Network ID, 20 bytes of the key hash and 4 bytes of the checksum). As most of the times the user inputs the destination Bitcoin address with a keyboard, an alphanumeric representation is a good option. A first approach would be to use a Base64 encoding. 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 but it does not include the previously mentioned symbols becoming a better solution and the one currently used. Therefore, the 25 bytes long Bitcoin address is represented by 26-34 alphanumeric characters in a more user-friendly manner. The shorter addresses result from the fact that they start with zeroes and as the zeroes are not encoded the address representation gets shorter.

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

15 Algorithm 2.1: Bitcoin Address Generation [50]. In the equations the _ operator represents con- catenation. P ublic key ← ECDSA-secp256k1( X _ Y ); V ersion ← 0x02 W 0x03 W 0x04; Key hash ← RIPEMD-160[ SHA-256( V ersion _ P ublic key ) ]; Network ID ← 0x00 W 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] P ublic key ← 50863AD64A87AE8A2FE83C1AF 1A8403CB53F 53E486D8511DAD8A04887E5B2 3522CD470243453A299FA9E77237716103ABC11A1DF 38855ED6F 2EE187E9C582BA6; V ersion ← 0x04; Key hash ← 010966776006953D5567439E5E39F 86A0D273BEE; Network ID ← 0x00; Checksum ← D61967F 6; Bitcoin address ← 16UwLL9Risc3QfP qBUvKofHmBQ7wMtjvM

From Algorithm 1, it is easy to notice that the amount of possible Bitcoin addresses is limited by the RIPEMD with 160 bits. The key hash is always 160 bits long which means there are 2160 or about 1, 460, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000 different possible addresses. If two different persons accidentally generate the same public key (Address Collision), it means that both of them also have the corresponding private key and as such can access and steal the funds from each other, however, “it is more likely that the Earth is destroyed in the next 5 seconds, than that a collision occur 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 Key Hash (P2PKH) [52]. As the name says, in this type of transaction the payment recipient is represented by a hash of the public key, just as it was described in subsections 2.2.1 and 2.2.2. As this is the standard 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 transaction identifier; 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 may be added to the block chain, and vi) the size of the transaction message in bytes. The outputs are instructions for sending bitcoins and are composed of two fields: i) a value, that indicates the amount of bitcoins to send, and ii) a ScriptPubKey which is the “locking script that determines the conditions that need to be met in order for a transaction to be spent” [53]. The inputs are references to outputs from previous transactions and are composed of three fields: i) the transaction identifier of the referred output, ii) an index that specifies the output in the outputs array of the referenced transaction, and iii) a ScriptSig which is the “is the unlocking script that solves the conditions placed on the transaction by the ScriptPubKey” [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 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 output used to this end is called change. In Figure 2.4, a simplified example of a Bitcoin transaction is represented, where the payment amount is 13.0 bitcoins. To achieve this value, one or more inputs are needed with referenced outputs totaling at least the desired amount. This way, the current transaction uses two inputs, one that points to a coinbase transaction and references the output with index = 0, and another that points to a previous transaction that is stored in the blockchain and references the output with index = 1. The total input amount totals 13.8 bitcoins (12.5 + 1.3 = 13.8) and the transaction fee is set to 0.5 bitcoins, which leads to a change of 0.3 bitcoins (13.8 − 13.0 − 0.5 = 0.3) that are sent back to the sender. Once the current transaction is added to the blockchain, the outputs that were referred by the used inputs are now considered “spent” so they cannot be used again in future transactions.

Coinbase transaction

ID = 90b18... Current Transaction Output Value=12.5 scriptPubKey ID = ff1ab... Input Output ID=90b18… Value=13.0 Index=0 scriptPubKey Previous transaction in blockchain SigScript Output (change) ID = 72c5b... Input Value=0.3 ID=72c5b… scriptPubKey Input Output Index=1 ID=6f5c1… Value=2.5 SigScript Index=0 scriptPubKey Output (fee) SigScript Input BTC=13.8 Value=0.5 scriptPubKey Output Value=1.3 Output BTC=13.8 scriptPubKey

Output (fee) Value=0.03 scriptPubKey

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, use it to sign the transaction message and thus produce its digital signature; because the digital signature is included in the transaction message itself. Hence, instead of using the whole message as the subject of the signature, all inputs included in the transaction message are signed, which in turn will be embedded in the correspondent ScriptSig. This script will include besides the signature, the public key (Bitcoin address) 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 validate it before transmitting it further, and miners validate it before including it in a new transaction block. The validation 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 have to meet in order to receive the payment. For example, the ScriptPubKey can define that the transaction recipient could be anyone, or can also require that in order to spend the bitcoins an input must be signed with private keys that belong to different people [52].

17 Previous Transaction Sent to the Recent Transaction address=1ErxK... ID = 84c24... ID = 13aaf...

Input Output Input Output ID=5e7ca… Value=0.001577 ID=84c24… Value=0.0015 Index=0 scriptPubKey Index=0 scriptPubKey SigScript SigScript Output Output (change) Input Value=0.00159956 Value=0.0000512 ID=d264e… scriptPubKey scriptPubKey Index=2 SigScript Output (fee) Output (fee) Value=0.0002 Value=0.0000258 scriptPubKey scriptPubKey

scriptPubKey ScriptSig

OP_DUP Signature: OP_HASH160 3045022100c51d512928e13d61a30 Hash160: ceb77db70e5d0b565d559f5491edb 980c312d019510eac5c25715a97ae 7cf2312ae84ae06f022050f0710d43 1732f395302 6a6dc8bf415dc3b86c7b66b0be534 OP_EQUALVERIFY 2e257b86cb5fcb203f693632801 OP_CHECKSIG Public Key: 0438c73f3ba716a2b214141da57eb 60f6fdbe8652bb5a05944010087a5 1460a16dcdad7bf71608e0cba3125 d00c94656c18b130150bd92cbc1ea a73fd266b04c85

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 contained in the ScriptSig and ScriptPubKey, take as an example the Figure 2.5 where two real transaction that are stored in the blockchain are presented. One of the Previous Transaction output, in the amount of 0.001577 bitcoins, is destined to the user that generated the Bitcoin address=1ErxK.... This output is later referenced by an input in a more Recent Transaction. When a miner or a peer verify the Recent Transaction validity, they use the input’s ScriptSig and its referenced output’s ScriptPubKey. The content of former script is the Signature and the Public Key, and the content of the latter script is the sequential operations that must be used in order to verify that the output can be used. The verification procedure makes use of a last-in first-out (LIFO) stack to store the arguments of the operations, each operation remove the first items of the stack and stores back the result. In the case of Figure 2.5, the Signature and 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 operation but 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 Recent Transaction is performed from the address that the output was destined to. Lastly, the only items that are left in the stack are the Signature and the Public Key, which are used to verify (OP_CHECKSG) if the 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 wallets were created to assist in and handle the execution of those processes. A Bitcoin wallet is a digital wallet analogous to a physical wallet, but instead of storing currency, it stores all the private keys associated with the generated Bitcoin addresses, signs transactions, and consults the blockchain to inform of the available funds in each address. However, as with physical wallets, there are different types wallets

18 available to fit different needs as shown in Table 2.1. In this way, some of the main functions may be disabled 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 are meant to be used on a daily basis, and thus are typically connected to the Internet for a faster and more convenient use, cold wallets remain offline for less exposure and are used for long-term storage of large amounts of bitcoins. For example, a Light Desktop Wallet is a hot wallet as it needs to access the blockchain for everyday use. Hot wallets are not very secure, since their connection to the Internet makes them quite susceptible to a variety of attacks. On the other hand, the Paper Wallet corresponds to a cold wallet, because it is just a piece of paper where a key-pair is printed on. Cold wallets are very secure 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 not only 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 to take certain precautions. The wallets that generate Bitcoin addresses store the correspondent private keys, and this means that if those keys are lost so are the corresponding bitcoins. To avoid this kind of 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 the possibility to generate multiple private keys, and consequently different Bitcoin addresses, from one seed with a given deterministic derivation rule. The wallets that implement this functionality are denominated Hierarchical Deterministic (HD) wallets. Thus, the user could create different Bitcoin addresses through an algorithm that, if it is given the same conditions, would always generate the same addresses. This allowed the user to do just a backup of the seed instead of all the private keys that are used as they can be generated again from the seed.

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

The host of the wallet becomes - Initial setup takes a long time due the large a full node of the Bitcoin net- Bitcoin size of the blockchain; work, which means that the - Bitcoin Core [58]. - Private keys are stored on the host giving Clients whole blockchain is downloaded more control over the bitcoins. and kept locally.

Light Operates in a similar manner as - Setup is relatively fast; - Multibit [59]; Desktop the Bitcoin Clients but it does not - Private keys are stored on the host giving - Electrum [60]; Wallets download the full blockchain. more control over the bitcoins. - Armory [61].

A third party stores the private - Entrusts the security to the service provider Online - Coinbase [62]; keys in their servers which are who has full control over the client’s bitcoins; Web - Xapo [63]; accessible through an account - Flexible as most of them have mobile and Wallets - blockchain.info [64]. created for their services. desktop versions available.

Used in mobile devices. It could - The most convenient wallet; - Bitcoin Wallet [65]; Mobile be an application that works as - Can have enhanced features: use of QR - Mycellium [66]; Wallets a Light Desktop Wallet or as an codes and NFC. - Copay [67]. Online Web Wallet.

- Can easily be generated from different web- Physical sites; Most used website to gen- A piece of paper that has the pri- Wallets / - Does not allow to consult the balance on erate this type of wallet: vate and public keys printed on. Paper their own; https://www.bitaddress.org/ Wallets - Could be very secure if well protected.

A secure hardware device is re- - Very secure; - Ledger Nano [68]; Hardware sponsible for the generation and - Does not allow to consult the balance on - KeepKey [69]; Wallets storage of keys and the signing their own; - Trezor [70]; process. - Resistant to computer viruses. - BitSafe [71].

19 2.2.5 Security Features

The Bitcoin protocol has in its implementation some considerations regarding the security and privacy of its users. For example, when performing a transaction if the destination address is not transcribed exactly and becomes invalid, it is likely that the transaction will be rejected. In fact the possibility of that not happening is approximately 1 in 4.29 billion [72]. However, if by chance the mistyped address already exists, then the transaction is considered valid and once that is broadcasted to the network it cannot be reversed. One important characteristic of Bitcoin that affects both the security and privacy of its users is the blockchain. The fact that this ledger is publicly available gives the users and merchants more security against frauds, like identity theft or credit card fraud. However, as the ledger is stored permanently on the network some effort is required to protect the privacy of the users. Even though Bitcoin addresses do not reveal any kind of information about the user, it is still possible, given a address to deduct the purchase history by analyzing the blockchain. For that reason, it is advised to use a Bitcoin address only once, and when performing a transaction the change should be redirected to a new address generated by the user. This way, it is much harder to trace back the addresses through the available transactions to 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 for a every-day use. The increase of flexibility of a wallet usually conditions the security that it provided, for example, a Online Web Wallet has a very flexible usage but as the private keys are entrusted to a third party 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 try to associate the Internet Protocol address to the data requested in the network. Despite all the protection that Bitcoin offers, ultimately the level of security and privacy provided depends on the good practices adopted 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 all kind of payment services and systems. It has been exploited to create a framework that would allow any application to use a privacy friendly online remote prepaid payment system while guaranteeing that its user’s sensitive data is protected [73]. To that purpose, it was taken advantage of the secure environment provided by the TrustZone to handle the security sensitive operations and to store the private data. Another system that was proposed and relied on the TrustZone secure storage, consisted in a mobile ticketing system that offered an additional security layer over the recipients stored on devices leading to a more trusted proof of purchase [74]. Recently, TrustZone has also been considered for the improvement of Bitcoin Mobile Wallets, but no experimental results or security analysis have been provided [75, 76]. In 2014, Rivetz®, a company that is focused on providing solutions that are used as an intermediate layer between the hardware security that is built-in the devices and the application developers [77], started to develop a standard API which 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-party Bitcoin 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 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 Development Kit (SDK) [81]. The two previous solutions are quite similar, the one proposed by Rivetz is more general and is e-commerce oriented while the one proposed by Ledger is more specific to Bitcon and thus it could also be more efficient. Both of them use the same TEE implementation,

2.4 Summary

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

21 request TAs to perform security sensitive operations. Both applications have the possibility of exchanging data 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-spending problem. To achieve this feature, an ongoing chain of transactions is used, where transactions are inserted in a chronological order after providing a proof-of-work. In this way, a ledger is created that contains 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 with more detail, such as the process of generating Bitcoin addresses, the transaction process itself, and the different types of available Bitcoin wallets. Finally, the existent work was described. As the features of TrustZone are very attractive to payment services, 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 two companies that have invested in this area by developing SDKs that could be used alongside with TAs to improve the security of the existent Bitcoin Mobile Wallets.

22 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 In this chapter, it is proposed the use of a TrustZone-enabled platform as a Bitcoin wallet. The practical interest of such proposal arises from using the secure storage to store sensitive data, and from taking advantage of the reliable secure cryptographic services provided by the Secure World to perform some of the Bitcoin functions. First, the secure storage prevents certain attacks which are possible to occur 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 the hardware level, no dictionary attacks are possible. The usage of the cryptographic services provided by the Trusted OS, that were developed by cryptographers with high expertise, also mitigates possible side-channel attacks. Another benefit of this configuration is the integrity check that can verify if a piece of 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 can assign different, secure, and exclusive regions of memory to different TAs, which creates the possibility of 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 will allow 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 divided in two steps: the first step consists in analyzing the existent types of wallet to find the one more prone to benefit from the use of the TrustZone features, and in the second step a base wallet will be chosen according 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 two types of wallet that stand out from the others: i) Mobile Wallets due their usage flexibility and complete functionality; 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 addresses balances and broadcast the performed transactions. This type of wallet can be considered the most flexible 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 stored online or on the cloud of some service provider. In contrast, Hardware Wallets, being cold wallets as mentioned in the subsection 2.2.4, are one of the most secure types of wallets, since they consist in a 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 third party software to check the balance associated with an address and to broadcast the transactions to the blockchain. Taking into consideration all the characteristics referred, the type of wallet that will benefit the most when integrated into a TrustZone-enabled platform is the Hardware Wallet, because it will not only allow to increase even more the security and trust upon the data processed and stored in the device, but it will also enable a trusted execution environment which other applications that require the same level of security can make use of, extending, in this way, the flexibility of this type of wallet and creating a more complete solution almost similar to the one provided by Mobile wallets. The fact of not having the possibility to check the balance on its own could be mitigated with this solution, as the wallet could be

24 easily expanded to check the blockchain when connected to a hosting computer that is online. Thus, the need 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 examples of Hardware Wallets given in Table 2.1 were effective candidates as a base for development, so the next 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 were considered resided in the fact that Trezor and Ledger Nano are the most popular Hardware Wallets in the market, KeepKey is the most aesthetically pleasing, user-friendly and has support for more than one type of digital currency, and lastly BitSafe is a Hardware Wallet that started as a small open-source project within the Bitcoin community and ended up being commercialized by a company called Butterfly Labs®, and despite not being yet available in the market there is a great interest in the product from the users side [84, 85, 86, 87]. As the final version of BitSafe is not yet available, in this work the development prototype will be considered, which was greatly discussed and disclosed in a Bitcoin related blog [87] by its original creators. In Table 3.1 it is given a brief description about each one of the referred Hardware Wallets as well as its strengths and weaknesses. Whenever possible the available specifications and the base price are presented.

Table 3.1: Main Hardware Wallets. Hardware Base Description Features Advantages Disadvantages Specifications Wallet Price

A small device with a - HD wallet; screen and on-board - The seed consists in 24 En- - Released in glish words randomly gener- buttons that allow to - Screen and buttons offer ex- August 2014; ated; display and confirm tra protection and verification; - Relatively expensive; - Processor: ARM - Requires a PIN code for Trezor transactions. Provides a - Web interface that enables - Need of a USB cable Cortex-M3 core spending bitcoins. Incorrect $99 [70] web interface to check standalone operation; to connect the device (120 MHz) with guesses increases the wait the balance and insert - Open-source [88] (License: to the host computer. custom developed time between guesses by a the transaction into the GNU LGPLv3 [89]). system; blockchain. It is one of power of two; - Internal entropy the most popular and - To the seed can be added a source. used Hardware Wallets. 25th word defined by the user.

A very simple designed device that support mul- - Simple usage, user-friendly - Relatively expensive; tiple digital currencies. - HD wallet; design, and metal body; - Not as easy to trans- - Released in It has a screen and a - The seed can be 12, 18 or 24 - Screen and buttons offer ex- port as the alternative September 2015; KeepKey on-board button to dis- English words randomly gen- tra protection and verification; products due the de- - Processor: ARM $99 [69] play and confirm trans- erated; - Support for multiple digital vice dimensions; Cortex-M3 core; actions before signing - Requires a PIN code for currencies; - Need of a USB cable - Internal entropy them. It was originally spending bitcoins. - Open-source [90] (License: to connect the device source. forked from the Trezor GNU LGPLv3 [89]). to the host computer. project.

- HD wallet; - Not as user-friendly A very affordable Hard- - The seed consists in 24 En- as the other options; ware Wallet imple- glish words randomly gener- - Accessible price; - Cannot verify the - Released in mented on a smartcard ated; - Small and convenient for- outgoing transactions December 2014; with a format similar to - Requires a PIN code for mat; as it lacks a screen; - Microproces- Ledger Nano a flash-drive. It is one spending bitcoins. Three in- - Security card to compen- - Requires a private sor inside a CC $39 [68] of the most popular and correct guesses will wipe the sate the lack of a screen; or trusted computer to EAL5+ [91] smart- used Hardware Wallets device; - Integrated USB connection setup the wallet; card; despite the need of a - Provides a security card as to the host computer; - Requires Chrome - Internal entropy third party software to be a 2-factor authentication to be browser to be used; source. used. used when performing trans- - Not fully open-source. actions.

- User-friendly format; A practically platform- - HD wallet; - Screen and buttons offer independent implemen- - The seed is randomly gener- extra protection and verifica- tation of a minimal Hard- ated and can be displayed in a tion; ware Wallet in small encrypted form; - Source-code practically BitSafe form factor. It has - Requires confirmation for ev- platform-independent; - Still a prototype; - Released in Development a screen and on-board ery sensitive operation; - Provides a basic application - Seed is displayed as March 2013; N/A Prototype buttons to display and - Possibility to encrypt every that enables standalone a byte array. - Internal entropy [87] confirm transactions and wallet; operation; source. sensitive wallet opera- - Possibility to have hidden - Integrated USB connection tions. It also provides a wallets which existence can- to the host computer; basic application to send not be confirmed without the - Open-source [11] (License: the transactions to the correct encryption key. blockchain. BSD 2-Clause [92]).

25 There are three main criteria that will be taken into account when selecting the base wallet: i) the possibility 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 the platform where the wallet is implemented. These selection criteria were chosen taking into account that what is expected from a base wallet is the possibility to enhance its security through the use of TrustZone, and at the same time increase its flexibility. Therefore, in order to make use of the TrustZone security features some changes into the base wallet functions are needed, and to have that possibility it is necessary that the source-code of the base wallet is made publicly available and that its license allows modifications to it. The Hardware Wallet processor is also an important factor as it is needed a processor with the TrustZone technology enabled, or a base wallet whose hardware and firmware source-code are publicly availably so that it can be ported to another platform that has a TrustZone-enabled processor. In this way the second criteria is not critical but rather convenient. The last criteria is based on the level of dependency that the wallet source-code has on the platform where it is deployed, which is a very important factor as, herein, in this dissertation, 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 selection criteria. 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 attacks infeasible, using a seed composed by twenty-four common English words decreases the probability of error in its typing and makes the seed representation more user friendly, and the possibility of adding a twenty-fifth word defined by the user gives more protection in case of the device being stolen together with 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 an ARM Cortex-M3 core [93] which, unfortunately, does not implement the TrustZone technology, and as the developed source-code has a considerable level of dependence on the same platform the process of porting it becomes more cumbersome. As the source-code of the KeepKey Hardware Wallet was initially forked from the Trezor project most of its security features and characteristics are the same. The main difference between them lies in the design: while KeepKey has a more robust, steady and user friendly design, Trezor has a more fragile construction. However, as Trezor has been on the market longer than KeepKey, it is considered more secure 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 most used mainly due the its low commercial price. Like Trezor and KeepKey it displays the seed in 24 common English words and requires a PIN code for spending bitcoins. The main difference is that in the event of three consecutive incorrect guesses of the PIN code, it erases the entire memory of the device as a precautionary measure. As a way to address the lack of a display, it is provided a security card that is used as a 2-factor authentication for confirming transactions. However this measure does not protect against mis-indicated output transactions as without a screen it is not possible to confirm that the amount of the transaction is correct. This Hardware Wallet requires a trusted computer to be setup and a Chrome browser to work, which are its main disadvantages. Moreover, for a everyday use it would require the user to always carry the security card along with the wallet. As a final remark about this wallet, it is not open-source so there is not any chance to make any kind of modifications to its source-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 have some of the other candidate’s security features, it is considerably secure. It has the option to display

26 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 located on the device, and the most critical operations like formating the wallet also require the introduction of a PIN code. A very good characteristic that this wallet has and which makes it stand out is its platform-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 development prototype but only about the intermediate boards that it was tested on. However, both the firmware and the 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 can be stated that the Ledger Nano Hardware Wallet is not an option for the base wallet as it is not possible to modify its source-code. The Trezor and KeepKey Hardware Wallets had their code developed and optimized for the platform that they are implemented on and as such using a different platform would require 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 provides good security features and it is fully open-source. In this way, as the BitSafe’s development prototype is considered the most promising base wallet it is the one that is chosen to play that role. In the Table 3.2 more details about some of its main characteristics can be found.

Table 3.2: BitSafe’s development prototype main characteristics [87]. - Cold wallet; Classification - Hardware wallet.

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

- 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 is Features done, 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.

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

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

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

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

27 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 to identify which are the major modules that it is made of and how its storage is partitioned. Through the division 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. The storage is actually one of the most sensitive components of any security application, as it usually stores confidential and private information, which if compromised could lead to dire consequences. Thus, an understanding of the base wallet storage constitution is essential to guarantee that the data stored, such as private keys, are well protected. Moreover, this categorization is used to support the design process of 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 communication protocol between the hardware device and the host, and the features that it provided, it was needed to examine 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 components will 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 Global Partition, where the general information about the Hardware Wallet is stored, and the other one is called Accounts Partition, where all the created wallets are stored. In turn, each wallet is divided into two sections, 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 cryptographic salt, while the other section is unencrypted and contains general content about the wallet. However, it is important to notice that, if the user chooses to not use a password the sensitive data is stored in an unencrypted form.

Storage Wallet Constituition 0 - Number of Addresses 64 Entropy Pool Padding 96 Entropy Pool Reserved Encrypted Global Checksum 112 Seed Partition - 128 Checksum Device UUID Version 144 - Reserved 512 Unencrypted Name Accounts Paritition Wallets UUID 1536

Figure 3.1: On the left it is displayed how the Storage is partitioned, and on the right it is shown the information 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 used as a source to produce cryptographically secure random numbers. To avoid any faults with the entropy pool, it also stores its checksum (Entropy Pool Checksum). The last thing that it includes is a Device UUID that it is attributed to each Hardware Wallet for identification purposes. Furthermore, in Figure 3.1 the 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 revisions of some Atmel atmega328p chips (that chip was the first target of BitSafe) had reliability issues with storage in that area”1; ii) “the 112 - 128 hole is so that there is room for a bigger pool checksum, if that becomes necessary”1; iii) “The large hole from 144 - 512 was reserved for future expansion of the entropy 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 Bitcoin addresses are generated, or the Padding which corresponds essentially to random bytes that are used to discourage known-plaintext attacks. The Number of Addresses is an encrypted variable that indicates the number of Bitcoin addresses that were already generated from the Seed, and as such, it is used to know the number of iterations that are needed for the next time a new address is requested. Another encrypted field of great importance is the Checksum, which is the resulting SHA with 256 bits hash of wallet’s contents, and allows that any unauthorized modifications to the remaining fields to be easily detected. For example, when the user changes from the current wallet to another that it is stored on the device, it is performed the SHA with 256 bits upon the contents of the loaded wallet, and if the obtained hash differs from the one that is stored in the Checksum field, then it is known that the wallet was 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 possible future features, it is also included an encrypted Reserved field. There are a couple of other variables that are stored in an unencrypted form, such as the Version field, which can have one of three possible values: “encrypted”, “unencrypted” or “nothing there”. If the user defined a password for the wallet, it means that the sensitive information is “encrypted”, otherwise if the user opted to not use a password the 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 but chose to “hide” it by setting the field to its default value, creating, in this way, a plausible deniability about the wallet’s existence. As mentioned before, along with the password it is used a cryptographic salt to generate the keys used in the encryption/decryption process, that salt is the Wallet’s UUID unencrypted field, which is also used as a way for the host to identify the Wallet. The two remaining unencrypted fields are the Reserved field and Name field, the former is not actually used and is reserved for a possible future feature, while the latter is purely used with an informative purpose, which makes it not essential for 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 encloses functions to manage the Storage, from the ones that are used to set the encryption key of a specific wallet, to the ones used to sanitize each partition. Moreover, it includes the wrapper functions used to create new Bitcoin addresses. In Table 3.3 the main functions of this module are specified, and a brief description of the same is also given.

Transaction Functions: All the needed functions to parse the Bitcoin transactions received from the host are enclosed in this section. It also includes the wrapper functions that are used to sign each transaction and to encapsulate it into a format that is compatible with the Bitcoin protocol. In Table 3.4 the 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 are responsible 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 other functions for various purposes, for example: to create the PINs that are used to confirm certain operations, or to help generate Bitcoin addresses. The main functions of this module, as well as a brief description of the same are presented in the Table 3.5. The function generateDeterministic256(), is used to 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 generate the new one. Instead, it is used an iterative and deterministic process where it is used the seed as the source and the number of addresses already created as the number of iterations to be performed. “The advantage 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 the master public key [11]. According to the BIP 0032, it is on the master public key that it is applied the deterministic algorithm to generate the new Bitcoin addresses. The master public key is stored in a buffer, since it is often used, and this buffer optimizes its access time, as one does not have to access non-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, for example, when parsing transactions. The AES, which was already mentioned in the Storage, is used to encrypt and decrypt certain elements of a wallet. The key that is used for that process is generated by the Password-Based Key Derivation Function 2 (PBKDF2). The RIPEMD with 160 bit it is used to create Bitcoin addresses, as described in subsection 2.2.2. The HMAC - SHA with 512 bits is used in the process of generating pseudo-random deterministic numbers, which is suitable for generating Bitcoin addresses 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 and sign transactions, as it was described in subsection 2.2.3.

Cryptographic Operations Cryptographic Operations

SHA-256 AES RIPEMD-160 SHA-256 AES RIPEMD-160

Wallet Storage SHA-512 HMAC-SHA-512 Wallet Storage HMAC-SHA-512

Storage HMAC-DRBG Storage HMAC-DRBG HMAC-SHA-256 ECDSA HMAC-SHA-256 ECDSA

Write PBKDF2 Cache PBKDF2

(Pseudo-)Random (Pseudo-)Random Wallet Transaction Wallet Transaction Number Generation Number Generation Functions Functions Functions Functions Functions Functions

General Wallet Functions General Wallet Functions

a) b) 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 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.

Parses a variable-sized integer within a transaction, which is commonly used to represent getVarInt() counts 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 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.

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

Version of getRandom256Internal() which uses the persistent entropy pool from non- getRandom256() 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 transaction fee.

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 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 ones that interact directly with the platform’s hardware and peripherals. The functions related with getting the user’s confirmation, or displaying information into the device’s screen need to be adapted to the target hardware. 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 host device are presented. These packets translate, in a certain way, the functions that are provided by the wallet 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.

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

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.

Get the master public key and chain code, which consists in the PACKET_TYPE_GET_MASTER_KEY last 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 functionality and security, through the use of the TrustZone features, with the aim of creating a secure and reliable TrustZone-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 most critical parts that should be implemented in a more secure environment. Herein, it is assumed that the underlying TrustZone-enabled device implements GlobalPartform’s APIs, which guarantee the portability of the proposed implementation, and the scenario explained in subsection 2.1.1 is applicable, where it was mentioned that it should have a Trusted OS, in order to create a more powerful system that boosts

33 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 get encrypted, which means that the Seed, Number of Addresses already generated, Padding, Checksum of the wallet, and the Reserved field become completely vulnerable, creating the ideal scenario for an attacker. If the BitSafe device gets stolen, the attacker can use it without any restrictions as the data is no longer protected by a password. Moreover, even if the device only stores one wallet whose addresses does not have any funds associated, the attacker can still use the Seed and the Number of Addresses already generated to create all the possible Bitcoin addresses that will ever be used by the wallet. That information can be valuable if the user continues to use the same wallet3, in which case he can steal any bitcoins that the user will receive in any one of those addresses. This situation can also be replicated in the 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 can easily modify the content of the Entropy Pool and then calculate its new checksum, which he would use to replace the existent one in the Entropy Pool Checksum field. If this happened, the Entropy Pool would become compromised, and consequently the random numbers that are generated by using its information would also be compromised. Additionally, if the attacker could invalidate the source of randomness, 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 function responsible for generating the PINs is called generateInsecureOTP(). Another unencrypted field that the attacker could tamper with, if he had the possibility of reading and writing into the BitSafe’s storage, is the Version field. In the case that the user opted to use a password the Version field is set to “encrypted”, however if an attacker changes it to “nothing there”, he creates a plausible deniability about the wallet existence, and as “updating the version field for a hidden wallet would reveal where it is” [11] the user is not able to change it, which means that the password cannot be changed either. In this way, the attacker has invalidated the possibility of changing the encryption key of 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 same password 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 million passwords 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 sensitive data is vulnerable to dictionary-based attacks, where an attacker tries a large amount of the most typical passwords for decrypting the data, until he finds a suitable one. Once that happens, the attacker has full access 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 applications in the same device, to the presented vulnerabilities it would be added the ones associated with software solutions, where the mentioned attacks can also be performed by malicious applications. It is easier to an application that runs in the same device as the BitSafe software to access and tamper with its storage than an attacker who would need physical access. Due to these vulnerabilities, it is proposed to add an extra layer of security and protection, which is 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 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 the guarantee that the confidentiality and integrity is maintained. For that, it specifies that each operation that acts on the storage and is not successful, does not produce any change, and it also mandates the following requirements for the secure storage4:

1.“ The Trusted Storage may be backed by non-secure resources as long as suitable cryptographic protection is applied, which MUST be as strong as the means used to protect the TEE code and data itself ” [30]. In some implementations of the TEE, the secure storage space is located in the Normal World’s file system, where the data is stored encrypted with a key that is located in a secure region of the device’s memory, which is only accessible to the Secure World. This means that whenever a TA wants to update some stored data, it first needs to fetch into the Secure World the disk sector that contains the correspondent data from the Normal World’s file system. Once the 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 device as when the data was created” [30]. This requirement gives the guarantee that even if the secure space data and the TA are copied to a different device, it is still not possible to access the data, as it 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 of encryption and decryption of the secure storage space data should not be performed with keys that are fully accessible by the TAs. In this way, one TA cannot interfere with the data created by another TA;

4.“ Each TA has access to its own storage space that is shared among all the instances of that TA but separated from the other TAs” [30]. This requirement along with the previous one, allows to have an isolation between different TAs, which is ideal for the wallet proposed herein as it is intended to have 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 is accepted that the actually physical storage may be in an unsecure areas and so is vulnerable to actions from outside of the TEE” [30]. This means that the TEE provides a certain level of protection for when one tries to replace the secure storage with outdated data.

The implementation of all these requirements can mitigate the vulnerabilities before mentioned for the BitSafe’s storage. A user not using a password is no longer considered a threat as the data is still stored in an encrypted form by the TEE in the secure storage space with a key that is securely generated and stored. This also covers the cases where the user chooses a weak password, since the additional encryption makes dictionary-attacks impractical, namely for the situations where an attacker exploits available bugs on the Normal World, or when he tries to intercept the communication made between the two worlds. The fields that were stored unencrypted, such as the Version field, Entropy Pool, and Entropy Pool Checksum, are now encrypted and, in fact, the whole BitSafe’s storage is encrypted. This removes the possibility of easily tampering with those fields and, thus, it becomes much more difficult to 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 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 region where the wallet storage is located, it is still not possible to decrypt the data as the key is hidden from the TAs itself. Moreover, as each TA has its own individual and secure memory space, malicious applications cannot 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 storage space has now an associated overhead, due the encryption and decryption operations. In this way, a secure write-cache is also proposed, where intermediate results are stored, and later flushed into the secure storage, to speed-up the write and read operations. The write-cache consists of a buffer with the size of a disk sector located in secure memory. Whenever there is data to be written, it is checked if the correspondent disk sector is already available in the cache. If it is not, the disk sector is loaded into the cache and the previous content is flushed. For the reading process, if the data that is requested is on the disk sector that is loaded on the cache, then it is read from there, and otherwise, the data is read directly from the secure storage. At this point, it is possible to deduce that the secure execution of the Cryptographic Operations is 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. The GlobalPlatform’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 256 bits 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 use the API for that function, and instead implement it manually, as a way to maintain the portability and platform-independence of the final solution. In addition, the RIPEMD with 160 bits, HMAC - DRBG, and PBKDF2 should also be implemented manually as they are not provided by the API. For the remaining cryptographic operations, it is proposed to use the provided Cryptographic Operations API as it offers a secure and trustworthy execution. The OEMs can improve even further the security of those functions by 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 most critical functions. Additionally, for the ones that process and/or produce sensitive data, it is also proposed to remove the possibility of invoking them outside the Secure World. However, it is important to notice that, for certain functions, it is not possible to remove its invocation from the Normal World, because either they provide features that are specified by one of the packets described in the Table 2.1, or they are invoked by other functions that are not proposed to be transfered to the Secure World. For the functions that have only part of their code used to process/create sensitive data, it is proposed to transfer to the Secure World only those sections. For the remaining functions, it is proposed to maintain their implementation in the Normal World, because either they are not critical, or they use functions that are already fully or partially proposed to be implemented in the Secure World. In this way, it is expected to not increase too much the size of the TA that will provide the General Wallet Functions. This is because it is important the amount of code that runs on the Secure World to be minimal, so that it can be easily reviewed, analyzed, and the quantity of bugs be minimized. Regarding the Wallet functions, it is proposed to transfer the current wallet cache to the Secure World to avoid any tampering with the same, and maintain the confidentiality obtained by transferring storage to the Secure World. Based on the descriptions provided in Table 3.3, the following propositions are also made:

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

• readWalletRecord(): It is proposed to fully transfer this function to the Secure World and remove the 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 the Normal World, it would mean that the some of previously described vulnerabilities were present;

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

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

• initWallet(): It is proposed to only transfer the essential section of this function to the Secure World. To initialize a wallet functions like calculateWalletChecksum(), readWalletRecord(), and deriveAndSetEncryptionKey() are invoked, which are fully implemented in the Secure World and without the possibility of invoking them through the Normal World. This means that the section of the 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 function resets some of the execution variables that are used, as well as the master key buffer, which are operations 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 possibility of 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 Secure World. The section that should be transfered is related with the functions that it invokes and are proposed to be fully implemented on the Secure World, which make also the most critical section of this function;

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

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

• makeNewAddress(): It is proposed to fully transfer this function to the Secure World. As it was already 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 with the process of generating new addresses, it is proposed to transfer this function to the Secure World;

• getMasterPublicKey(): It is proposed to fully transfer this function to the Secure World, since it needs 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 the possibility of invoking it from the Normal World. This is one of the most critical functions as it allows to get the private keys associated with every Bitcoin Addresses ever generated, thus it should only be executed inside the Secure World and without the option of invoking it in the Normal World. In this way, the private keys would never leave the TEE, strengthening the security features of the proposed wallet;

• getAddressAndPublicKey(): It is proposed to fully transfer this function to the Secure World. The public keys are generated from the correspondent private keys, which means that this function needs to access the private keys stored in BitSafe’s storage, and as it is proposed to restrain the access 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. This function 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 packets presented in the Table 3.7;

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

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

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

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

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

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

38 has to do with the fact that the private key is processed. Moreover, this function is only needed inside the Secure World as it is only invoked by functions that were proposed to be transfered to the 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 World and remove the possibility of invoking it from the Normal World, since it sanitizes the master key buffer. As the master key buffer is located in the Secure World there is no need of this function in the Normal World;

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

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

• getEntropyPool(): It is proposed to fully transfer this function to the Secure World. This function has 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 and accesses the Seed field, both of which are only available in the Secure World. For these reasons it is proposed to transfer this function to the Secure World;

The final propositions are related with the platform dependent functions, GlobalPlatform’s Trusted User 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. As this function is used to get cryptographic strong random numbers it should be guaranteed that it is not tampered with. The GlobalPlatform’s TEE Internal Core API provides a function to generate secure random numbers. In this way, it is proposed to use that function implemented in the Secure World;

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

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

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

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

39 Cryptographic Operations Cryptographic Operations

SHA-256 AES RIPEMD-160 SHA-256 AES RIPEMD-160

Wallet Storage SHA-512 HMAC-SHA-512 Wallet Storage HMAC-SHA-512

Storage HMAC-DRBG Storage HMAC-DRBG HMAC-SHA-256 ECDSA HMAC-SHA-256 ECDSA

Write PBKDF2 Cache PBKDF2

(Pseudo-)Random (Pseudo-)Random Wallet Transaction Wallet Transaction Number Generation Number Generation Functions Functions Functions Functions Functions Functions

General Wallet Functions General Wallet Functions

a) b)

Figure 3.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 implemented in 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 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 with the 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 by any 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 can be 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 allows to detect unauthorized changes to the BitSafe’s source-code. In this way, the trust upon the wallet is increased 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 benefit more when integrated into a TrustZone-enabled platform. It was concluded that Hardware Wallets were the ones more prone to increase their security and functionality. Among the different wallets available for the chosen type, the most popular ones were considered for the base wallet. For those, three selection 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 was implemented. Each candidate was analyzed according to the selection criteria, and their strengths and weaknesses. The BitSafe’s development prototype was considered the most fitted and, as such it was the one chosen for the base wallet. Then, a more detailed analysis was performed regarding the base wallet, where it was described each 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 TrustZone features were proposed, in order to create a TrustZone-backed Bitcoin Wallet with increased security and functionality. It was proposed to make use of the trusted storage, and of the available APIs to

40 perform cryptographic operations. It was also proposed to execute the most critical operations only in the Secure World by implementing them in TAs. For example, regarding the Wallet Functions, the functions related with getting and setting the cryptographic keys should only be handled inside the Secure 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 their critical 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 the whole wallet. For the Pseudo-Random Number Generation Functions, the ones that process the data of the Entropy Pool should be safely executed in the Secure World to avoid tampering it. Finally, the Cryptographic Operations should exploit the provided APIs to obtain cryptographically strong random numbers, which is an important requirement in several cryptographic implementations. Moreover the usage of the APIs, enable the circuit vendor to implement their versions of each cryptographic operation in a way that minimizes the possibility of side-channel attacks in their platform, further improving security.

41 42 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 Conguration ...... 48 4.3.2 Implementation Details ...... 53 4.4 Experimental Results ...... 55 4.5 Summary ...... 59

43 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 will be presented. Then, as it is intended to exploit the TrustZone technology to the most, the software stack that 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 will also 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 and procedure 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 years ago, and it is not know exactly which hardware was used. Furthermore, as there is no information about the processor that was used, even if there was the possibility of obtaining it there would be no guarantee that would support TrustZone. Nevertheless, as all the code is publicly available and there is the possibility of modifying it, since the underlying license allows it, the base wallet can be deployed in a different platform whose processor supports the TrustZone technology. Therefore, the next step is to choose 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-A5 2009 Cortex-A7 2011 Cortex-A8 2005 ARMv7-A Cortex-A (32-bit) Cortex-A9 2007 Cortex-A12 2013 Cortex-A15 2010 Cortex-A17 2014 ARMv8-A Cortex-A32 2016

Cortex-A35 2015 Cortex-A53 2012 Cortex-A (64-bit) ARMv8-A Cortex-A57 2012 Cortex-A72 2015 Cortex-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 processor would be the one that has implemented the ARMv8-M architecture, as it was designed focusing on security 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, but due its relevance it was also included. 2From the seventh generation of the ARM’s architecture, ARMv7, three different architecture profiles were defined: Application profile, Real-time profile, and the Microcontroller profile. Each ARM architecture and core refer to the first letter of the profile for which they were designed.

44 most of them have restricted access or none at all to the TrustZone technology, which is imposed by the OEMs itself due security reasons. Moreover, some of them have proprietary implementations of the TEE 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 they have 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 used for 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 main characteristics of these boards are summarized in the Table 4.2, from which it is possible to observe that all of these boards are suitable since they fulfill the minimum requisites imposed by the base wallet: they have 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. Processor’s Maximum Development Board Processor RAM Flash memory Architecture Frequency

Xilinx Zynq-7000 AP Dual ARM Cortex-A9 512 MB 256 Mb Quad-SPI SoC ZedBoard ARMv7-A 667 MHz DDR3 [104] MPCore. Flash

HiKey Board (HiSilicon 1 GB or 2 ARM Cortex-A53 Kirin 620) ARMv8-A GB 1.2 GHz 8GB eMMC Octa-core. [105] LPDDR3

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

- Cortex-A72: - big cluster: Dual-core 1.2 GHz; ARM Juno Board ARMv8-A Cortex-A57 or Cortex-A72; 8 GB -Cortex-A57: 64MB NOR Flash [107] big.LITTLE - LITTLE cluster: DDR3L 1.1GHz; Quad-core Cortex-A53. -Cortex-A53: 850MHz

The main differences between the platforms that are presented in Table 4.2, besides the amount of RAM and Flash memory, resides in the processor’s architecture and on the cores that make use of it. Both the Xilinx Zynq-7000 AP SoC ZedBoard and Freescale iMX53-QSB have processors with the ARMv7-A architecture [108] but, while the former uses two Cortex-A9 cores, the latter only uses one Cortex-A8 core. In turn, the HiKey Board (HiSilicon Kirin 620) and the ARM Juno Board, have processors that implement the ARMv8-A architecture; in the former, eight Cortex-A53 cores are used, and in the latter 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 to provide maximum compute performance [109]. The internal differences in the microarchitecture between big 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-bit instruction set. It “broadens the ARM architecture to embrace 64-bit processing and extends virtual addressing, building on the rich heritage of the 32-bit ARMv7 architecture upon which market leading cores 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 an official ARM development board which means that it is highly supported and has a good amount of documentation available [107]. Moreover, ARM created this platform with the intent of offering hardware and 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 wallets, and thus are most relevant for this proposal. At the present moment, there are three variants of this board, the last version is the ARM Juno-r2 board which has an ARMv8-A big.Little architecture, with a 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 it is the one that will be used. Nevertheless, it is important to mention that despite the chosen platform, the development 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 have an Trusted OS whose implementation was in accordance with the GlobalPlatform’s APIs in order to create 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 Normal worlds. OP-TEE [21] provides both of them, and at the moment it is the only one that supports the ARM Juno Board. Its implementation is based on a proprietary solution that was initially created by ST-Ericsson® and later acquired and maintained by STMicroelectronics® [21]. In 2014, Linaro® started a 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 its maintenance. Nevertheless, as project is open-source it is also supported by developers from all over the world who make ongoing contributions. During the development of the OP-TEE, three main goals were taken into account [14]: i) to provide a 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 small amount of on-chip memory; and iii) to provide a portable solution that could be easily implemented in different architectures and hardware. To accomplish these goals the TEE is implemented according with the GlobalPlatform TEE System Architecture specification [28]. For the Normal World, BusyBox is used as the operating system, since it was mainly developed to be used on embedded devices with low computational power. In the Secure World, that role is fulfilled by the OP-TEE OS whose size is about 244 KB. It is important to note that the code for the Trusted OS should be minimal not only to occupy the smallest possible space in memory but, since it comprises the trust anchor, to also be easily reviewed and 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 implemented by the OP-TEE Client, which provides the Client API as defined by the GlobalPlatform TEE Client API Specification [29] for the CAs, so they can communicate with the Trusted OS whenever one wants the secure 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 Storage access. The OP-TEE Driver is a Linux Kernel TEE driver that handles the communication between Normal World’s user space and the Secure World. Lastly, the Trusted OS, Secure Monitor, and the TEE Internal Core API are implemented by the OP-TEE OS, the latter having the GlobalPlatform TEE Internal Core API [30] into consideration. Unfortunately, the GlobalPlatform Trusted User Interface API Specification [31] is not included as its implementation is not fully developed. Besides the presented software stack, OP-TEE also has available a TEE sanity test suite, which is denominated xtest [111].

46 h edn rcs rmtescr trg pc shnldi iia anr[1] ntesame the In [113]. manner similar a in handled is space storage the secure In the from process messages. reading (RPC) The Calls it Procedure written, Remote be Supplicant by to sent data new are the commands has called TA component the secure updating a Once of process World. space. the Normal storage represented System the secure is to the it a back for 4.2 invoke it system will Figure sending file In and World’s data More Normal implementation. the the mentioned. similar also of a was use provides storage the OP-TEE secure referred the was of it implementation specifically, possible a presented, were storage 3 ihEeuinEvrnet(E)i yoy o the for synonym a is (REE) Environment Execution Rich nscin33 hr h eurmnso the of requirements the where 3.3, section In oudt h aaadecyttewoeds etr h nrpinpoesi ade by handled is process encryption The sector. disk whole the encrypt and data the update to eevstemsae n trsteecytddt codnl nothe into accordingly data encrypted the stores and messages the receives ytmCall System Privileged space User space Application Generic Supplicant TEE Storage iue42 PTEscr trg rhtcue[14]. architecture storage secure OP-TEE 4.2: Figure hog the through ARM TrustZone iue41 PTEsfwr rhtcue[112]. architecture software OP-TEE 4.1: Figure Normal OS e Manager Key Client Security API Client Wrapper APIs ( Optional OP OP - - enabled Chipset TEE Driver - TEE Client with Application OS supportOS nenlAPI Internal )

Secure hn h nrpe aaaogwith along data encrypted the Then, .

omnEeuinEnvironment Execution Common lblltomsTEItra oeAPI Core Internal TEE GlobalPlatform’s 47 hc ntr ilivk prtosi the in operations invoke will turn in which , Application Trusted 1 Monitor Secure ( Individual Application Space Individual crypto , Hardware Resources timers Internal API Application OP Trusted TEE Core , HAL watchdog - 2 TEE , . fuses Functions TEE , Security omlWorld Normal Service ...) E ieOperation File REE OP-TEE OS iu ieSystem File Linux

o h secure the for Privileged space User space the , E File TEE TEE 3 . requirements, it was mandated the secure storage to be bound to a particular device. The OP-TEE achieves 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), which is a per-TA key and is used to encrypt and decrypt a third key, the File Encryption Key (FEK), which is the final key used to encrypt and decrypt the data stored in the secure storage space [113]. The ability to hide sensitive key material from the TAs itself is also guaranteed as they do not have access to the SSK key, thus they cannot compromise the TSKs attributed to the others TAs. Lastly, OP-TEE also provides to each TA its own individual application space, which is an essential feature as it is planned to add the possibility 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-backed Bitcoin Wallet, which is divided in two steps. The first step consists in setting up the chosen platform in order create the ideal development environment, which includes installing the software stack and the needed tools for a more convenient development process, as well as performing the necessary tests to guarantee that everything is working properly. The second step corresponds to the porting of the base wallet 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 of a 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 Power Management 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 HBI0262D for 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 the MB folder for each revision;

• SOFTWARE: A folder that includes the SoC software images. A few examples are the System Control 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 card should be modified accordingly. Besides the default motherboard configuration, the board does not provide 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 get and setup the compatible file systems [115]. For the implementation of the presented proposal, it was opted to use the Linaro Tracking Kernel (Latest) with OpenEmbedded LAMP filesystem [115], as it had the 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 to add the OP-TEE software stack. At the early stages of this dissertation, the version of OP-TEE that was

48 available was the version 1.1.0, whose installation required to cross-compile4 all the software stack that was provided in a set of different repositories stored on Github [14], and then to update the SD card and the 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 World software, which includes the Secure Monitor, as well as some interface standards, such as the Power State Coordination Interface (PSCI), Trusted Board Boot Requirements (TBBR) and SMC Calling Convention [117];

• linux-linaro-tracking: This is the repository that contains the Linux kernel with the modifications made 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 it was mentioned by the following warning posted in the OP-TEE’s Github page [118]: “Warning! This setup is currently broken, bl30.bin and bl33.bin doesn’t exist on the URLs stated any longer. We are working with a fix and once ready, we will replace this section and instead put Juno board within the repo section below. Until resolved, we will keep the information below for reference”. The problem that was described indicated that the SCP runtime image (bl30.bin) and the UEFI firmware (bl33.bin) were not available anymore in the usual sURLs used by the script. As it was referred before, certain files are needed to configure the Juno motherboard, and should be included in the SOFTWARE folder because they are part of the SoC software images. As a solution to this problem, firstly previous versions of the missing files taken 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 the source-code of the remaining files of the OP-TEE software, and compile them for the ARM Juno board were available, once again, at OP-TEE’s Github page [118]. However, after the download process, and during 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 kernels versions. 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, and it 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) to be 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 folder called arm-plat-vexpress, which was then used to replace the predefined folder in the compilation script.

After solving these two problems, the software stack was successfully compiled. The next step was to 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 the host. In this specific case, the host would be a Linux machine where code is compiled, and the target would be the ARM Juno board, which is were the code will be executed.

49 process as mandated by OP-TEE [14]. However, once that was done, the board would always be interrupted during the booting process. The reason for that to happen was related with the missing files that were replaced, which were not compatible with the remaining files that were on the SD card or on the file system. To remove this incompatibility problem, it was analyzed the content of every file that was in the pre-built binaries, in order to find useful information about the versions of the files that were used upon the creation of the same binaries. A file named juno-latest-oe-uefi-20160125-1708.txt, contained abbreviated hashes (the first few hexadecimal characters) of the last commit5 that was made for every repository 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 these modifications, 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 the with remaining ones. As there were not any additional information about them. The same procedure, of replacing the missing files, was also applied with multiple configurations, where different versions of the missing 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. This release included a brand new way of compiling the source-code for the ARM Juno board. Therefore, it also had a new associated script. Previously, it was mentioned that there were some files that should be updated in the file system, but as described, there were some incompatibilities between the versions of the files that were used. In this way, with the new approach, OP-TEE opted to use an internal file system that was built during the compiling process and integrated in the ramdisk.img file6. The previous problems that resulted during the compiling process no longer appeared. Instead, the following warning was shown:

• WARNING: It wasn’t possible to open optee.ko and optee_armtz.ko for read: The optee.ko and optee_armtz.ko files are the kernel modules that are used to implement the OP-TEE Linux Driver. 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 compiled files, the OP-TEE Linux Driver would not work. Thus, to solve this problem, the optee_linuxdriver repository was compiled and downloaded separately. Then, the resulting files were added to the original 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 kernel by default. This was the reason why the optee_linuxdriver repository was not included in the source-files of this version. The warning only appeared because some verifications that were used in the previous versions were not removed. Nevertheless, the compilation process was successful and the files for the SD card were updated without any problem. Fortunately, the board no longer was blocked during the booting 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 executing the 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 the SHA 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 • 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 are two generic drivers, both are generated during the booting of the kernel, and are located in the dev folder 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 discussed with the OP-TEE developers [121]. It was concluded that the OP-TEE node in the device tree7 was missing, which meant that its firmware was not recognized by the board. This problem was never detected because the software stack was never tested on the most recent revision of the ARM Juno board, but only on the previous ones. Unfortunately, no solution was provided. Nevertheless, enough information to find one was given. The file juno.dts, which was mentioned in the discussion, consisted in the device tree file of the first revision of ARM Juno board (r0). When searching for the device tree file for the revision of the used board, it was detected that it was missing from the source-files. The only other existent device tree file was for the second revision (r1). Thus, after some research and analysis of the content of mentioned files, it was realized that it was possible to create the file for the last revision by modifying the one from the previous revision. For example, there are only a few differences between the 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 the ARM Juno-r2 board hardware. To complete the solution a binary of the modified file was still needed to be included in the SD card, as it was one of the files that should be updated. To generate it, the Makefile that processed existent device tree files was modified to include the new one that was modified. After this 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, the tee-supplicant, found the new generic drivers making the board operational with the OP-TEE software stack. All this procedure was reported back to the OP-TEE developers [121], and the proposed modified file 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 code that can be used as a CA that implements the fundamental principals discussed in the same API. Taking into account the provided code, it was developed the corresponding TA, where the requested functions were implemented. One of the operations that was requested consisted in generating a cryptographic key, and in a later stage use is to perform an encryption operation. According to the GlobalPlatform’s TEE Internal Core API, whenever it is intended to securely store a key into the file system, Persistent Objects should be used as the key container. In this way, the operation flow consisted in storing the generated 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 Secure World, and the key extracted and used. When this function was tested, it was noticed that the key was successfully generated, but it was not correctly stored on the persistent object, because when the key was 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-TEE developers [16] along with the TA code that was used to detect the problem. Later, the origin of the problem 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 correct functionality of the OP-TEE software stack. All the remaining requested functions by the CA were implemented and tested successfully, thus it was considered that the most critical features of the software stack were working properly. Nevertheless, during the development of previous TA it was realized that its associated development cycle, 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 into the OP-TEE’s file system. As the file system is included in the ramdisk.img file, the TA must be placed in the software stack source files. After including it, the software stack must be compiled again so that the file system with the TA is included in the ramdisk.img file. Then, the SD card must be updated with the new 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 only provides the bare essencial, it does not include the possibility of using the SSH and SCP.The addition of those features would allow to simplify the development cycle of the TAs, as their integration could now be 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 not possible with the current setup. In this way, and to efficiently develop TAs, support for the SSH and SCP features was added. After a careful research, it was found that the Dropbear [122] software package was a good option to be used 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 the use of the Ethernet port, but for some reason the board could not have access to the Internet. After performing 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 configurations were made manually: to set the IP address, and to set the route the ifconfig and route commands were used. Another problem that was found resulted from the cross-compilers used to compile the Dropbear source-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 on the ARM Juno-r2 board. A numerous of different cross-compilers and configurations for Dropbear were used 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 a connection, 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 not included, thus it could not recognize the user. From this point on, it was adopted a new approach where it was searched for a cross-compiler that would indeed include the necessary libraries to the binaries that it generated. One of such compilers was the arm-buildroot-linux-uclibcgnueabi-gcc, which could be obtained by using BuildRoot 2016.02[123], that consists in a set of Makefiles that allow to generate a defined cross-compiler. After compiling the Dropbear source-files with this new cross-compiler, the resulted binaries were integrated into the existent software stack on the ARM Juno-r2 board, and finally there was the possibility of using the SSH and SCP features. All the process taken to generate the final binaries 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 files that would update the SD card, was upgraded to the GCC 5, and that change required a copy of quite a few more files than before to the file system. As a consequence, there was an increase of

52 the ramdisk.img file size that exceeded its predefined Juno memory flash reserved location, it changed from 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 into the Juno’s flash memory were modified and rearranged. The file that contained those addresses was called images.txt. The methodology followed for the modification of the addresses was: i) Analize and understand the structure of the images.txt file; ii) verify how the flash memory is distributed between the images described in the file; iii) change the addresses by calculating the minimum amount of space needed for each one of the images, until enough space is available for the ramdisk.img; and iv) update the 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], and now 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, with the 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 it was originally designed consists only of implementing those dependent functions. A description of these functions was also given in Table 3.6. Some of them are related with the presentation of information to the user, while others are meant to process the information received from the user. There are also functions 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 usage of 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 display and receive sensitive information with the guarantee that it was not maliciously modified. The ARM Juno-r2 board supports the use of a Liquid Crystal Display (LCD) screen and keyboard. However, as mentioned in section 4.2, OP-TEE does not provide an complete implementation for it. Nevertheless there has been a growing effort in that direction [124]. Since this project is not yet finished, it is not possible to benefit from the GlobalPlatfrom’s Trusted User Interface API. In this way, and to reduce the cost of the developing process, it was opted to not use a display and keyboard wired and integral to the 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 the host’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 configuration is 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 transfered to a platform that provides an implementation for that API. Regarding the functions nonVolatileRead(), nonVolatileWrite(), and nonVolatileFlush(), which should act upon the platform’s storage, they will in fact operate on the write-cache that was proposed in the section 3.3. This cache is fully implemented in the Secure World, and as it was descried, it consists in a buffer with the size of a disk sector, where the data that comes from the Normal World is written. If the disk sector correspondent to the one where the data is supposed to be written is already loaded on the buffer, the buffer is updated with the new data. Otherwise, the disk sector that is currently on the

53 buffer is flushed into the secure storage, and the correct disk sector is loaded, and only then the buffer is updated with the received data. The size of the buffer was chosen to be the same as the size of a disk sector, because for most storage devices it is faster to update an entire sector than only a portion of it. The implementation of this cache was based on the ones that were available for the platforms were BitSafe was tested by its original authors. Meanwhile, the storage is implemented by using the GlobalPlatform’s TEE Internal Core API. In this API it is indicated that the secure storage stores Persistent Objects. Each one of them has an associated Data Stream, which can store large amount of data. In this way, BitSafe’s storage is a data stream of a persistent object, which includes all the partitions depicted in the Figure 3.1. The size of the data stream was 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(), and when 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 of this function uses an hardware True Random Number Generator (TRNG) whenever the platform where it is implemented on provides it. The ARM Juno-r2 board includes a “Trusted Entropy Source” which provides 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-TEE make 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 an operation handler that is obtained by using TEE_OperationHandle. This handler is then used as an argument for the subsequent function calls. The SHA with 256 bits, AES, and HMAC - SHA with 256 and with 512 bits are specified in the API as multi-staged operations, in which one function is used to initialize the operation, another to feed it with data and another to finalize it. For SHA with 256 bits, TEE_DigestUpdate() and TEE_DigestDoFinal() were applied (there is no initializer function); for AES, 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() were used. For the remaining cryptographic operations, OP-TEE provided implementations for the PBKDF2 and 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 by few implementations of the TEE. Since this proposition was designed to be as platform independent as possible, while still providing high levels of security, these operations were manually extended to the Secure World. For the RIPEMD with 160 bits, as it was not available in any API, its source-code was also 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 the Secure 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 from the 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 World and the Secure World for when performing an operation. The process flow was already described in the subsection 2.1.3, however it was not mentioned which were the functions that were used from the GlobalPlatform’s TEE Client API specification. There were few options available to allocate the region of memory that would contain the arguments of the operation, but the method chosen consisted in creating a buffer in the Normal World with the arguments of the operation, and reference it using a structure called

54 TEEC_TempMemoryReference, which is provided by the mentioned API. This specialized structure is sent to the Secure World through the TEEC_InvokeCommand() along with other important information related 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 communication with 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 single TA called wallet_ta.c. There were two main reasons for this isolation. The first one is because it makes it easier to analyze and scrutinize the code of the functions that were designed to communicate with the Secure 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. In this way, duplicated code was removed, while at the same time providing a more structured and modular solution. This lead also to some minor adaptations to the structure of the original source-code, creating an easier to understand and more organized source-code. As a final remark, the final source-code of the developed TrustZone-backed Bitcoin wallet will be made publicly available on the 21st of October (due to procedures related with the submission of a paper for the ICISC conference), and in the meantime can 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, is made 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 the Wallet Storage, Cryptographic Operations, and General Wallet Functions are assessed according to the configurations presented in sub-figures 3.3.a) and 3.3.b). In other words, the original code which was ported into the ARM Juno-r2 board with the configuration depicted in Figure 3.3.a) is compared against the developed wallet with the configuration depicted in Figure 3.3.b). From this point on, the former will be denoted with the term Original Base Wallet (OBW), while the latter will be denominated TrustZone-backed Bitcoin Wallet (TBW). The methodology used to measure the performance of each component consisted in sampling its execution time, which is acquired through the use of the clock() function from the C native library, one hundred 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 Secure World, enabling the exact assessment of the overhead imposed by the TrustZone technology. It is also important to remind that the main goal of developing the TBW was not to improve the execution times of the 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 that are presented in Figure 3.1, the evaluation of writing and reading operations is executed independently for each one of them, considering their full length, for both OBW and TBW. More specifically, for the Global Partition 512 bytes are read and written, and for the Accounts Partition 1024 bytes are read and written. In the case of the TBW, due to the write-cache proposed in section 3.3, and whose details were given in subsection 4.3.2, two possible scenarios were considered for when reading and writing data into the secure storage space. For the write operation, as it always writes directly into the cache, the situation where the correspondent disk sector is already loaded was evaluated, as well as the other where it is

55 not, and as such it needs firstly to be fetched. Regarding the read operation: if the correspondent disk sector is already in the cache, the data is read directly from there, otherwise, it is read from the secure storage space. In this way, to perform a complete analysis of this module for the TBW, the performance of the write and read operations are measured for all the possible mentioned scenarios. In addition, the operation 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. In parenthesis the execution time increase in percentage of the TBW relative to the OBW is presented. TBW Function OBW Secure Storage Secure Storage + Write- Secure Storage + Write- Cache (block not loaded) Cache (block loaded) Write in Global Partition 34 129111 (+374136%) 106685 (+309133%) 128 (+271%) (512B)

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

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

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

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 the Accounts Partition are smaller than the ones associated with the Global Partition, even though the former is larger. This is related with the fact that the Accounts Partition is fully included in one disk sector, while the Global Partition is divided between two disk sectors. Therefore, when writing 1024 bytes of data into the former partition, the whole disk sector can be replaced directly8. However, when writing 512 bytes into the latter partition, the two whole disk sectors needs to be loaded, the respective data replaced, and afterwards the both whole sectors are written back on disk. The same principle applies to the reading operation. This situation does not apply to the TBW, due the way that the storage is implemented. The use of a Data Stream to store the whole BitSafe’s storage implies that whenever one intends to read or write it is needed to fetch the Persistent Object that has the Data Stream independently of the target partition. Moreover, as OP-TEE OS defines the disk sector size to 4096 bytes long, along with the fact that it stores the data aligned in memory [113], allows to fetch the one disk sector that contains the BitSafe’s storage into the write-cache. Thus, the execution time of the writing of 1024 bytes into the Accounts Partition can never be less than the execution time of the writing of 512 bytes into the Global Partition, because now the writing operation only depends on the size of the data to be written. When comparing the TBW with the OBW, it is visible that there was an increase in the execution time for the storage functions, but that was expected as the secure storage space adds an extra layer of encryption provided by the Secure World [113]. When the secure storage space is used directly, the overhead of the additional encryption process has a significant larger impact. After adding a write-cache, the effect of the overhead is greatly mitigated if the requested block is already in memory; otherwise, one has to update the cache, with the associated overhead of reading from or writing to the secure storage. In both cases, there is not any work around to improve the Flush data function, as it writes directly into the secure storage, where the entire correspondent disk sector must be decrypted first, then data is written from 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 Wallet

8Here it is considered that the 1024 bytes to be updated are located in a single disk sector

56 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 were measured 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 the previously mentioned operations, as it is depicted in Figure 3.2. The SHA with 256 is one of the most used Cryptographic Operations in the whole wallet, since it is used in multiple situations, including the computation of Bitcoin addresses, where two iterations of the algorithm are required. Thus, in order to have a better understanding of how it performs under different conditions, its execution was analyzed for different argument sizes in all of the operation stages, more precisely with 1 byte and with 100 bytes of data. Moreover, a special mode (FINISH-DOUBLE), where a full iteration of the SHA operation is applied after a first execution, was also assessed.

Table 4.4: Execution time of the used Cryptographic Operations. The values are presented in clock cycles. In parenthesis the execution time increase in percentage of the TBW relative to the OBW is presented. Function Mode OBW TBW

INIT (100B) 2 69 (+3350%) WRITE (100 B) 43 121 (+178%) FINISH (100 B) 30 122 (+306%) FINISH-DOUBLE (100 B) 134 (+106%) SHA-256 65 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 140 OPERATION (69 B) 173 (-13%)

DECRYPT (64 B) 157 (-80%) AES-XEX-128 794 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 is presented. The SHA with 256 bits and the RIPEMD with 160 bits were the only ones that were negatively affected for being executed in the Secure World. Regarding the SHA with 256 bits, is important to note that the execution time of the WRITE stage in the TBW is practically independent of the data size that is being processed. The AES in XEX mode with 128 bits function benefits from the same principle, as the encryption and decryption processes take the same time to execute in the TBW as opposed to what happens in the OBW. Moreover, it was proven to be much faster when the API provided by OP-TEE for the Secure World was used. This confirms that the use of standardized APIs is beneficial to obtain the maximum performance, since each vendor is able to implement the functions in the most optimized manner for the underlying hardware. The ECDSA and PBKDF2 where both manually implemented in the Secure World and their execution time has also improved largely. The RIPEMD with 160 bits was an exception, because despite of being also manually implemented in the Secure World, its execution did not improve. The reason behind it, is the additional overhead inherent with the communication between the Secure and Normal worlds, since the code was ported from the OBW, the implementation remains the same, and thus, the execution times should be similar. Lastly, the HMAC - SHA with 512 bits is

57 an operation that can be seen as the aggregation of two sub-operations: i) one that consists in setting the 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 motivation that lead to its separation was that in some functions this operation is successively called, and as most of them use the same key, it becomes more efficient to execute the operation separately from the key setting. Moreover, as the execution time of the OPERATION is faster in the TBW than in the OBW, when OPERATION is called repeatedly, the overhead of key setting becomes negligible and the TBW more efficient than the OBW. As the functions implemented by the components included in the General Wallet Functions module are used to provide the functionalities associated with the packets described in Table 3.7, the processing of those packets will be assessed instead. The measurements comprise the period of time since a packet is 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 execute an operation are presented. As it was expected, all the functions that directly involve reading or writing to the secure storage space had its execution time increased. For example, the function to format the storage was one of the most impacted as it performs multipass, low-level overwrites with random data in the full size of the wallet to guarantee that its final state is unpredictable, leading to a large overhead from the additional encryption layer. The functions to delete a wallet suffer from a similar issue, as it executed the same process but only in the specific region of the Accounts Partition where the wallet to delete is stored. On the other hand, the functions that do not directly use the secure storage space

58 had its performance improved. These reduced execution times result from the improvements previously described in Table 4.4. Furthermore, the functions involved in creating a new address and to sign a transactions are among the most important and used ones in the whole wallet, and the fact that these functions were able to execute in a faster and more reliable manner confirm the validity of the proposal presented in this dissertation. Lastly, in Table 4.6 a qualitative comparison between the OBW and the TBW is presented. Firstly, the OBW storage encryption was supported on a password provided by the user. As this type of systems can often be attacked using dictionary-based attacks, the decision to use TrustZone secure storage greatly boosted 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, the OP-TEE API was implemented taking into account the underlying hardware, which allows to provide an higher level of assurance against side-channel attacks. Furthermore, while the OBW used checksums to protect 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 with each other. Therefore, it is possible to extend the proposed wallet with other applications that need high levels of security, such as home-banking. Finally, it was seen that while the use of the secure storage deteriorated performance for some functions, the use of the OP-TEE API allowed for platform-specific optimizations that enhanced performance for cryptographic operations.

Table 4.6: Qualitative comparison between the OBW and the TBW. Resistance against Resistance against Code and data Extensibility Performance dictionary attacks side-channel attacks integrity

OBW      TBW     

4.5 Summary

In this chapter, the details for the implementation of the proposed improvements made in section 3.3 were described. As they exploited TrustZone features, a TrustZone-enabled platform was needed. In the 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 still have 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 development platforms for creating, testing, and debugging TAs, the ARM Juno-r2 board was chosen as the most suitable one to implement the base wallet. This platform was produced by ARM to offer developers a chance 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 did not include one, so the OP-TEE was used, which provided an implementation for OSs of the Normal and 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, while offering 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 and problems that surfaced from that process were described, as well as the solutions found. The proposed

59 changes contributed to the enrichment of the OP-TEE project, including the added native support for the ARM Juno-r2 board and the identification of some missing features on the existent software along with a test case for its detection. The whole process followed to adapt the existent configuration to a more programmer friendly setup was also described, including the possibility of using the SSH and the SCP features. This created the ideal environment for developing TAs, including the one that was used to create 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 APIs used to take full advantage of the TrustZone features. This chapter ended with the presentation and discussion of the execution times for the functions that operated upon the wallet storage, performed cryptographic operations, and executed the general wallet functions on the original base wallet and on developed wallet. It was concluded that the read and 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. Regarding the cryptographic operations, as most of them were implemented using the GlobalPlatform APIs, which enable platform-specific optimizations, their execution time improved, while others such as the SHA with 256 bits did not, but they took the same time to process the data independently of its size.

60 CHAPTER 5

CONCLUSION

Contents 5.1 Summary and Overall Conclusions ...... 62 5.2 Future Work ...... 63

61 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 in order to benefit from the enhanced security, it was intended to add the possibility of running multiple security 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 the developed 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 concept of two different virtual worlds. Each one of them has a unique vision of the SoC according to the security requirements associated with it the Normal World, consists in the common execution environment for the normal applications, whereas the Secure World, which is a TEE, is where TAs are executed with a high level of integrity and confidentiality supported by the underlying hardware. Afterwards, Bitcoin was introduced and described as a peer-to-peer network that allowed to perform transactions between two 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 and robust payment system, makes it very attractive to the normal user, and specially to the business and financial 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 with enhanced security features, where sensitive data is processed in a manner that ensures integrity and confidentiality. However, up until now, there is not any related work that provides experimental results or security analysis for such solution. Thus, this dissertation contributes to make up for the shortfall that was existent in this study field. Among the different types of Bitcoin wallets available, an Hardware wallet was chosen as the base wallet type, since it had proven to be the most prone to increase its security and functionality when used along with the TrustZone technology. For the base hardware wallet itself, the BitSafe development prototype was considered as the most fit because it presented features which were in agreement with what was intended for the final solution: the source-code was independent from the platform where it was implemented, and it was fully available as open-source. The next step consisted in carefully analyzing its main modules, namely the Storage, Cryptographic Operations, and General Wallet Functions. From this analysis, it became possible to identify parts of the system that could be improved, and critical sections that should be executed in a more secure environment. Thus, proposals where made that consisted in transferring the sensitive operations to the Secure World to be integrated in a unique TA. These proposals would guarantee that the handled sensitive data, the critical operations and the stored data could 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 wallet by allowing multiple security-sensitive applications to run simultaneously in the same device without compromising the level of added security. In this way, a base wallet was proposed with increased security, 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 of consumer electronics, and as such it will eventually also be used for Bitcoin wallets. To provide the board with the full capabilities to make the most out of the TrustZone features, the OP-TEE software

62 stack was used that provides an implementation for the Normal World OS, as well as for the Secure World OS, with accordance to standardized GlobalPlatform’s APIs. However, the installation process of this software into the chosen board was not standard and involved some modifications to its source files, from where several contributions resulted to the OP-TEE project. This enabled to have an ideal environment for developing TAs, and more importantly, it created the necessary conditions to port the base wallet into the ARM Juno-r2 board and implement the proposed modifications. It is important to note that the chosen board did not condition the implementation and development processes, as the use of standardized APIs, along with the platform-independence of the BitSafe’s source-code, allowed to 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 were negatively affected due the additional encryption layer added by the OP-TEE when storing the data into the 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 improved its 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 due to an extra level of encryption, cryptographic operations were made more efficient through the use of standardized APIs, that enable vendors to implement these operations in a more optimized and secure manner.

5.2 Future Work

During the development of this dissertation it was not possible to use the GlobalPlatform’s Trusted User Interface API as it was not yet fully developed by OP-TEE. However, the addition of this API would greatly increase the security provided by the TrustZone-backed Bitcoin wallet that was developed. In such case, it would be possible to use a keyboard or touchscreen to have the user’s password entered without the risk of having as this communication would be handled directly by a specific TA. In the same manner, this API enables to display information in a screen guaranteeing, for example, that the value of the presented transaction is not tampered with. OP-TEE also provides the option of using a different implementation of the secure storage than the 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 than the default implementation that relies on the normal world file-system. However, there is not any formal documentation available, and since it is has not been explored enough it is still liable to bugs. When this system matures, if it becomes standardized, it could become an interesting additional feature of the proposed wallet. Recently, due the importance of the profiling techniques, OP-TEE started to make an effort to develop a benchmark framework [130] to provide with such features. Its use would allow to provide more accurate measures and, thus, confirm the validity of the assessment performed.

63 64 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, impacts and legislation,” in Proceedings of the 2015 Science and Information Conference, SAI 2015. 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 2014 Twelfth 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,” Applied Economics, 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,” ARM white 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 in August 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 [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 in August 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 [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 in September 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 Curve Domain 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 create an 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 in September 4, 2016).

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

67 [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] (Accessed in 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 September 6, 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 in September 5, 2016).

[60] Electrum, “Electrum Bitcoin Wallet,” "https://electrum.org/#home", 2016, [Online] (Accessed in September 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 September 5, 2016).

[63] Xapo, “Xapo - Bitcoin Wallet & Vault,” "https://xapo.com/", 2016, [Online] (Accessed in September 5, 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 [67] Copay, “Copay – Secure, Shared Bitcoin Wallet,” "https://copay.io/", 2016, [Online] (Accessed in September 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 in September 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] (Accessed in September 6, 2016).

[73] M. Pirker and D. Slamanig, “A framework for privacy-preserving on security en- hanced ARM trustzone platforms,” Proc. of the 11th IEEE Int. Conference on Trust, Security and Privacy 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 TrustZone technology,” 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 into Hardware Wallets,” " https://cointelegraph.com/ news/ledger-transforms-smartphones-into-hardware-wallets", March 2016, [Online] (Accessed in August 21, 2016).

[77] Rivetz, “About the Rivetz Team,” "https://rivetz.com/index.php/team,", 2016, [Online] (Accessed in September 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 [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 - BitSafe v1,” "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 September 15, 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 Methodology for 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 in September 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 [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 Cryptographic Protection 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 Comes to 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 in September 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] (Accessed in 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] (Accessed in 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 in September 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 [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 [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