secure iot for the future - esat.kuleuven.be · first of all, i would like to thank professor...

46
Secure IoT for the future A Degree Thesis Submitted to the Faculty of the Escola T` ecnica d’Enginyeria de Telecomunicaci´ o de Barcelona Universitat Polit` ecnica de Catalunya by Alicia Bel Ventosa Carried out at KU Leuven in the Department of Electrical Engineering (ESAT) In partial fulfilment of the requirements for the degree in Telecommunications Technologies and Services Engineering Advisor: Ingrid Verbauwhede Advisor: Esteve Pallar` es Leuven, June 2020

Upload: others

Post on 19-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Secure IoT for the future

A Degree ThesisSubmitted to the Faculty of the

Escola Tecnica d’Enginyeria de Telecomunicacio de BarcelonaUniversitat Politecnica de Catalunya

byAlicia Bel Ventosa

Carried out at KU Leuven in theDepartment of Electrical Engineering (ESAT)

In partial fulfilmentof the requirements for the degree in

Telecommunications Technologies and Services Engineering

Advisor: Ingrid VerbauwhedeAdvisor: Esteve Pallares

Leuven, June 2020

Page 2: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Abstract

Scientists estimate large-scale quantum computers will be publicly available within fewdecades. This will have a detrimental effect on the security of our digital world, especiallysecurity of applications that depend on public-key cryptography. An effort is going on todevelop quantum resistant cryptographic protocols in anticipation of the arrival of quan-tum computers. As part of this process, it is important to deploy such quantum resistantcryptographic protocols in many different platforms, especially resource constrained de-vices.In this project we aim to provide an evaluation of the performance of post-quantum KeyEncapsulation Mechanisms (KEM) and digital signatures integrated into Transport LayerSecurity (TLS) protocol and deployed in a resource constrained device. Specifically, wewill integrate post-quantum Saber, Kyber and Newhope KEM schemes together withDilithium digital signature into the embedded TLS open source library, mbedtls. To per-form this, the TLS handshake approach of the mbedtls library as well as certificates andtheir parsing have been modified to be able to handle post-quantum algorithms.The performance of such implementation will be measured with the code deployment intoRaspberry Pi 2 Model B, an embedded platform with an ARM Cortex-A7 processor. Inour experiments, we found how the integrated post-quantum schemes have algorithm andhandshake runtimes from one and up to two orders of magnitude faster than other classicalcryptography elliptic curve KEM and signature schemes.

1

Page 3: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Acknowledgements

First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my advisor at UPC, Esteve Pallares Segarra, forhis support and willingness to help.Next, I would like to thank my daily supervisors Angshuman Karmakar, Furkan Turanand Jose Maria Bermudo for their huge help and implication on the project.Additionally, thanks to all the people I have met here in Leuven, who have eased theprocess of living abroad and supported me in the fulfillment of this thesis.Last but not least, I would like to thank my parents, whose implication during my educa-tional period is one of the reasons why I have managed to get here.

2

Page 4: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Contents

1 Introduction 8

2 Background 102.1 Transport Layer Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.1.1 TLS design idea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.1.2 TLS handshake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.2 Cryptographic definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.2.1 Public-key cryptography . . . . . . . . . . . . . . . . . . . . . . . . . 122.2.2 Key Encapsulation Mechanism . . . . . . . . . . . . . . . . . . . . . 132.2.3 Digital Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2.3 Post-Quantum Cryptography . . . . . . . . . . . . . . . . . . . . . . . . . . 142.3.1 Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.3.2 LWE, LWR, Ring-LWE, Mod-LWE and Mod-LWR problems . . . . 152.3.3 Polynomial multiplication . . . . . . . . . . . . . . . . . . . . . . . . 162.3.4 Lattice-based KEM schemes . . . . . . . . . . . . . . . . . . . . . . . 162.3.5 Lattice-based digital signatures . . . . . . . . . . . . . . . . . . . . . 17

2.3.5.1 Fiat-Shamir signatures . . . . . . . . . . . . . . . . . . . . 17

3 KEM integration into mbedtls 193.1 Integration procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

3.1.1 Cipher suites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193.1.2 Key exchange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3.1.2.1 Key exchange characteristics . . . . . . . . . . . . . . . . . 203.1.2.2 Key exchange related functions . . . . . . . . . . . . . . . . 20

3.1.3 Modifications at the TLS handshake . . . . . . . . . . . . . . . . . . 223.2 Post-quantum KEM schemes . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3.2.1 Saber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253.2.2 Kyber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253.2.3 NewHope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

4 Digital signature integration into mbedtls 274.1 Integration procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

4.1.1 Message digest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.1.1.1 Message digests in mbedtls . . . . . . . . . . . . . . . . . . 284.1.1.2 SHAKE256 message digest . . . . . . . . . . . . . . . . . . 29

4.1.2 Signature algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.1.2.1 Signature algorithms in mbedtls . . . . . . . . . . . . . . . 314.1.2.2 Dilithium signature algorithm . . . . . . . . . . . . . . . . 31

4.1.3 Digital Certificates . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

3

Page 5: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

4.1.3.1 Key generation . . . . . . . . . . . . . . . . . . . . . . . . . 324.1.3.2 Key parsing and writing . . . . . . . . . . . . . . . . . . . . 334.1.3.3 Object identifier . . . . . . . . . . . . . . . . . . . . . . . . 354.1.3.4 Certificate generation . . . . . . . . . . . . . . . . . . . . . 36

4.2 Post-quantum digital signature - Dilithium . . . . . . . . . . . . . . . . . . 36

5 Performance evaluation 375.1 Platform deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

5.1.1 Raspberry Pi 2 Model B . . . . . . . . . . . . . . . . . . . . . . . . . 375.1.1.1 Modifications in the library . . . . . . . . . . . . . . . . . . 38

5.2 Code performance evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . 385.2.1 Cryptographic primitives evaluation . . . . . . . . . . . . . . . . . . 38

5.2.1.1 KEM schemes . . . . . . . . . . . . . . . . . . . . . . . . . 395.2.1.2 Signature algorithms . . . . . . . . . . . . . . . . . . . . . 39

5.2.2 Handshake evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . 395.2.2.1 Handshake runtime . . . . . . . . . . . . . . . . . . . . . . 405.2.2.2 Handshake message sizes . . . . . . . . . . . . . . . . . . . 40

6 Conclusion and future work 426.1 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426.2 Future work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

6.2.1 Further algorithms integration . . . . . . . . . . . . . . . . . . . . . 426.2.2 Optimized platform implementations . . . . . . . . . . . . . . . . . . 43

4

Page 6: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

List of Figures

2.1 TLS protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.2 TLS handshake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.3 Key Encapsulation Mechanism . . . . . . . . . . . . . . . . . . . . . . . . . 132.4 Traditional approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.5 Digital Signature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.6 Key Encapsulation Mechanism . . . . . . . . . . . . . . . . . . . . . . . . . 172.7 Digital Signature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

5

Page 7: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

List of Tables

5.1 Runtime of KEM schemes operations . . . . . . . . . . . . . . . . . . . . . . 395.2 Runtime of digital signature operations . . . . . . . . . . . . . . . . . . . . 395.3 Handshake runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405.4 Handshake message sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

6

Page 8: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Listings

3.1 Post-quantum KEM context . . . . . . . . . . . . . . . . . . . . . . . . . . . 203.2 Initialization function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.3 Key generation function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.4 Public-key obtention function . . . . . . . . . . . . . . . . . . . . . . . . . . 213.5 Shared secret and ciphertext generation function . . . . . . . . . . . . . . . 223.6 Shared secret obtention function . . . . . . . . . . . . . . . . . . . . . . . . 223.7 Server Key Exchange, server side . . . . . . . . . . . . . . . . . . . . . . . . 233.8 Server Key Exchange, client side . . . . . . . . . . . . . . . . . . . . . . . . 243.9 Client Key Exchange, client side . . . . . . . . . . . . . . . . . . . . . . . . 243.10 Client Key Exchange, server side . . . . . . . . . . . . . . . . . . . . . . . . 243.11 Premaster secret, client side . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.1 Message digest information . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.2 SHAKE256 information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.3 SHAKE256 context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.4 SHAKE256 init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.5 SHAKE256 free . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.6 SHAKE256 start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.7 SHAKE256 update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.8 SHAKE256 finish . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.9 SHAKE256 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.10 Dilithium pk information . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314.11 Dilithium context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324.12 Dilithium keyfile generation . . . . . . . . . . . . . . . . . . . . . . . . . . . 324.13 Dilithium public and private-key parsing . . . . . . . . . . . . . . . . . . . . 334.14 Dilithium public-key parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . 344.15 Dilithium public-key writing . . . . . . . . . . . . . . . . . . . . . . . . . . . 344.16 OIDs defines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354.17 OIDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355.1 CPU cycle count . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

7

Page 9: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Chapter 1

Introduction

Throughout history, hiding sensitive information from all those who are not the intendedrecipients has been one of the main requirements of communication. Following the inven-tion of computers and digital devices, the need for a cryptography standard to establishsecure communications became clear. This led to the creation of our current cryptographyinfrastructure, which will be referenced to as classical cryptography.Classical cryptography addresses both key distribution and encryption. Symmetric cryp-tography is currently used to perform encryption, being AES (Advanced Encryption Stan-dard) [1] the most commonly used algorithm. Key distribution and digital signatures, onthe other hand, are made using public-key cryptography, also known as asymmetric cryp-tography. The first published protocol for key distribution was Diffie-Hellman [9] keyexchange. Whitfield Diffie and Martin Hellman were also the firsts ones to describe thenotion of a digital signature scheme in 1976. It was not until 1989, however, when thefirst software package offering digital signature was published. It was developed using theRSA[26] algorithm.Asymmetric cryptography is based on the hardness of one-way mathematical functionssuch as large prime numbers factorization or discrete logarithm. A function is consideredone-way if it can be computed in polynomial time but an algorithm attempting to computeits inverse would succeed with negligible probability. The functions mentioned above arecompliant with this definition when considering all existing classical computers. There aretwo factors, however, that threaten the strength of these one-way functions, the inventionof Shor’s [27] algorithm and the rise of quantum computers.Shor’s algorithm, invented in 1994 by Peter Shor, is a polynomial-time quantum com-puter algorithm for integer factorization. Although large-scale quantum computers havenot been developed yet, the possibility of their building is recently becoming more realfor scientists. Some even predict that, large enough quantum computers to break clas-sical cryptography will be built within the next twenty years or so. If Shor’s algorithmor Proost and Zalka’s [24] application of the algorithm to discrete logarithm, were to bedeployed in a powerful enough quantum computer, classical asymmetric cryptography al-gorithms would be broken. All of this, together with the fact that our actual cryptographyinfrastructure has needed almost two decades to be deployed, has increased the interest inpost-quantum cryptography. An evidence of this growing interest is the process initiatedby NIST (National Institute of Standards and Technology) to standardize post-quantumalgorithms [23].Cryptography has a wide range of utilities in several fields, one of the main ones is thesecuring of communications on the Internet. Transport Layer Security (TLS), as the lead-ing communication protocol on the Internet, has an important role in this. Additionally,

8

Page 10: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

our society is gradually growing towards the massive connectivity of daily use devices. Inthis context, securing the communications between Internet of Things (IoT) devices hasalso grown in importance.This project will combine post-quantum cryptography, TLS and embedded devices. Thegoal is to integrate several KEM post-quantum schemes together with a post-quantumdigital signature, candidates of NIST standardization competition, into an open sourceembedded TLS library (mbedtls [17]). The chosen algorithms will be explained in de-tail in the implementation chapters. The integrated code will be deployed and tested inRaspberry Pi 2, providing an overview of the real-life practicality of the results.

9

Page 11: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Chapter 2

Background

This chapter will give an overview of the Transport Layer Security (TLS) and of somebasic cryptographic definitions. It will also introduce post-quantum cryptograpgy and thechosen post-quanum algorithms.

2.1 Transport Layer Security

Transport Layer Security (TLS) [8] is a cryptographic protocol that provides secure com-munication in a network and it is widely used on the internet. TLS is the evolution ofSSL (Secure Sockets Layer). The first version of TLS (1.0) was released in 1999 as anupdate of SSL 3.0 published in 1996, afterwards, versions 1.1, 1.2 and 1.3 of TLS werepresented. This project uses mbedtls library [17], a lightweight implementation of TLSprotocol, suitable to small resource constrained devices such as microcontrollers, whichalso handles cryptographic primitives and certificate manipulation. This library only sup-ports 1.2 and earlier versions of TLS, this is why this project will focus on TLS 1.2.TLS should be understood as an authentication framework rather than a single protocol,as it provides a structure for authentication and key-exchange negotiation. Its usefulnessresides in the fact that it does not fall in a naıve approach to communication security.That is to say, believing it is only about sharing keys between two endpoints, but quitethe contrary, the framework approach fulfils the main needs that secure communicationpresents. These include the negotiation of algorithms and parameters, the authenticationof endpoints, the integrity of exchanged messages and the protection from possible attacks,etc.

2.1.1 TLS design idea

As can be seen in Figure 2.1, TLS works above the transport layer and uses the Trans-mission Control Protocol (TCP). Figure 2.1 also shows how TLS protocol itself is dividedinto two layers. The record protocol works directly above TCP and is the one that handlesfragmentation and encryption. On top of it we find the handshake protocol which allowsobtaining symmetric keys and where the negotiation of features is performed. There isalso the change cipher suite specification protocol which signals transitions in encryptionstrategies and the alert protocol that handles errors. Finally, we find the application pro-tocol which forwards data from the application layer.The aim of this project is to integrate post-quantum cryptography in the Key Encapsu-lation Method and signature schemes provided by TLS . We will now focus on the TLShandshake which is the fragment of the TLS protocol that, with some modifications, will

10

Page 12: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

allow us to perform the integration mentioned above.

Physical Layer

Data Link Layer (MAC)

Network Layer (IP)

Transport Layer (TCP)

TLS

TLS record protocol

Handshakeprotocol

Changecipher spec

AlertApplication

Data

Application Layer (HTTP)

Figure 2.1: TLS protocol

2.1.2 TLS handshake

The TLS handshake occurs after a TCP connection is established. The handshake isinitiated by the client with the ClientHello message, which includes the TLS version andcipher suites1 supported by the client, together with a random number. The server replieswith a ServerHello where the chosen TLS version, the chosen cipher suite and the serverrandom number can be found. Afterwards, the server sends its SSL certificate which willallow to perform server authentication. Certificates also contain the server public-keywhich allows encryption. If required, for instance when the server has no certificate orit is only used for signing, the server will send the ServerKeyExchange message with thekeys needed to perform encryption and that were not present in the certificate. If it isappropriate for the chosen cipher suite the server may also require a certificate from theclient to be able to authenticate it. It will finally send the ServerHelloDone message toannounce the end of this step of the handshake.The client is then expected to send a response. It will first send its certificate if it wasrequested, then a ClientKeyExchange message whose content will be different for eachalgorithm agreed between the ClientHello and the ServerHello. This is the last step ofthe key generation and exchange, the specifics on how this is performed depends on thechosen cipher suite, but after this message both Server and Client will possess or be ableto generate the shared key. If the client has sent a certificate and it had signing ability,a digitally-signed CertificateVerify message will be sent to confirm the possession of theprivate-key. Next, a ChangeCipherSpec message is sent with which the client indicates theswitch to the negotiated cipher. The Finished message that uses the agreed algorithms,keys and secrets announces the end of the handshake on the client side. In response, theserver sends its own ChangeCipherSpec message and Finished message that again will use

1Set of algorithms that help secure a network connection, including a key-exchange algorithm, a sym-metric encryption algorithm and a message authentication code (MAC).

11

Page 13: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

the negotiated algorithms, secret and keys.At this point the handshake is finished and application data can be securely exchanged.The explanation above is graphically shown in Figure 2.2.

Client Server

ClientHelloServerHello(Certificate)(ServerKeyExchange)(CertificateRequest)ServerHelloDone

(Certificate)ClientKeyExchange(CertificateVerify)ChangeCipherSpecFinished

ChangeCipherSpecFinished

Application dataApplication data

Figure 2.2: TLS handshake

2.2 Cryptographic definitions

The goal of this project is to introduce post-quantum Key Encapsulation Mechanisms(KEM) and digital signatures into mbedtls. This section will provide a detailed expla-nation the KEM mechanism and the digital signature, as well as a description of thepublic-key mechanism needed to fulfill them.

2.2.1 Public-key cryptography

Public-key cryptography schemes, also known as asymmetric cryptography, are based onthe use of a pair of public-private keys in which the public one can be known by anyonewishing to send a message and the private one is only known by the owner. The generationof these keys is done through cryptographic algorithms based on the hardness of one-waymathematical problems, such as the discrete logarithm in which Diffie-Hellman is basedor the integer factorization used by RSA [26]. As will be explained in Section 2.3, the riseof quantum computers has compromised the validity of one-way functions used so far andhas forced researchers to find other mathematical problems which are not vulnerable toquantum computers.To use a public-key cryptography scheme, after generating the public and private keys,the owner must share its public-key so that anyone interested in sending a message can doit. The sender of the message is expected to encrypt the message with the public-key andsend the ciphertext. The owner of the keys will be able to decrypt the message using theprivate-key. This cryptographic scheme also allows the introduction of digital signaturesfor authentication.

12

Page 14: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

2.2.2 Key Encapsulation Mechanism

Key encapsulation mechanisms (KEM) use asymmetric cryptography to obtain a securesymmetric key. They also introduce a new method that avoids the need for paddingschemes which are traditionally used when applying asymmetric cryptography to obtainsymmetric keys. With KEM mechanisms, two parties agree on a symmetric key, to exem-plify we will be calling them Alice and Bob. To begin with, Alice generates a private-publickey pair. The public-key is available for Bob to send encrypted messages to Alice. Bobgenerates a random number from which he derives the symmetric key, using a key deriva-tion function such as a cryptographic hash. He then uses Alice’s public-key to encrypt therandom number and sends the ciphertext to Alice. Alice is able to decrypt the ciphertextusing her private-key. Finally, Alice derives the symmetric key from the decrypted randomusing the same key derivation function as Bob. This explanation is graphically representedin Figure 2.3. In Figure 2.4 there is a representation of the traditional approach to sym-metric key obtaining.

Alice Bob

Generate private-public key pairPublic key Generate random

Generate symmetric key from ran-domEncrypt randomCiphertext

Decrypt ciphertextGenerate symmetric key from random

Figure 2.3: Key Encapsulation Mechanism

Alice Bob

Generate private-public key pairPublic key

Generate symmetric keyApply padding to symmetric keyEncrypt padded symmetric keyCiphertext

Decrypt ciphertextReverse padding scheme

Figure 2.4: Traditional approach

2.2.3 Digital Signatures

A digital signature is a cryptographic scheme that uses asymmetric cryptography and isformed by a key generation function, a signature function and a verify function. Theimplementation of a digital signature between two communication parties provides:

13

Page 15: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

• Message authentication: When a signature is validated using the public-key of thesender it is assured that the signature is computed by the sender who is in possessionof the private-key.

• Data integrity: In case the data is modified by an attacker the verify algorithm willfail. Consequently, the receiver can safely discard the data assuming that it has beenaltered.

• Non-repudiation: The signer cannot deny the ownership of any data he has previ-ously signed.

We will now introduce the process followed to compute digital signatures, this explanationis graphically represented in Figure 2.5. Firstly, the signer has a public-key pair, in TLS,the public one will be distributed using certificates. He then takes the data to be signed andcomputes a hash from it, the hash will be then introduced into the signature algorithmfunction to compute the signature. The signature algorithm also requires the signer’sprivate-key to compute the signature. The signer then sends the data together with thesignature to the verifier. The verifier gets the data and, using the same hashing functionas the signer, computes the hash. He then takes the signature and the signer’s public-keyand runs the verify algorithm. As a result, the same hash than the one computed with thehashing function should be obtained. With the hash comparison verification, the signatureis finished.

Signer Verifier

Data

Hashingfunction

Hash

Signaturealgorithm

Signer’sprivate

key

SignatureData

Signature

Hashingfunction

Verifyalgorithm

Compare

Signer’spublic

key

Hash

Hash

Figure 2.5: Digital Signature

2.3 Post-Quantum Cryptography

For several years now, there has been a substantial amount of research on quantum com-puters. Their great potential comes from the fact that, while classical computers use bits

14

Page 16: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

(either 0 or 1), quantum computers use qubits which, with superposition2 and entangle-ment3 properties, allow to highly increase processing power.The breakthrough of quantum computers implies, however, a threat to all communica-tions that rely on classical cryptography. The integer factorization problem, the discretelogarithm problem and the elliptic-curve discrete logarithm problem are the three mainmathematical problems in whose hardness are based almost all classical asymmetric cryp-tography algorithms. The three of them, nonetheless, could be broken in polynomial timerunning Shor’s [27] or Proost and Zalka’s [24] algorithms in a powerful quantum computer.In light of the above, the need for post-quantum cryptography that provides secure asym-metric4 algorithms against quantum computer attacks becomes evident.During the past years, several post-quantum algorithms have been developed, for bothkey encapsulation mechanism and digital signatures. This section will provide a generaloverview of both types of post-quantum algorithms as well as an introduction to someconcepts needed to understand the nature of the algorithms.

2.3.1 Notation

Single polynomials are represented without markup, vectors are bold lower case and matrixare bold upper case. U represents a uniform distribution and βµ a binomial distribution

with parameter µ and standard deviation σ =√

µ2 . Zq is the ring of integers mod q with

representants in [0, q). Rq is the quotient ring Zq[X]/(Xn + 1) with n power of 2. For anyring R, Rl×k is the ring of l × k matrices over R.

2.3.2 LWE, LWR, Ring-LWE, Mod-LWE and Mod-LWR problems

Learning With Errors: The LWE problem was introduced by Regev [25] and is basedon the hardness to distinguish uniform random samples (a, u) ← U(Zl×1q × Zq) from the

same number of LWE samples (a, b = aT s + e) ∈ Zql×1 × Zq . Where s ← βµ(Zl×1q )

is a secret vector fixed for all samples, a ← U(Zl×1q ) are uniformly random vectors ande← βµ(Zq) are small error terms sampled from an appropriate error distribution.

Learning With Rounding: The LWR problem is a derandomized version of the LWEproblem and was introduced by Banerjee et al [3]. The error terms in LWR do not comefrom an error distribution but are deterministically obtained when scaling and roundingcoefficients modulo q to modulo p (p < q). The problem is therefore based on the hardnessof distinguishing uniform random samples as described above with the same number ofLWR samples of the form (a, b = bpq (aT s)e) ∈ Zl×1q × Zp, where a and s are of the sameform as the ones in LWE.

Ring Learning With Errors: The Ring-LWE is a more computationally efficient vari-ant of the LWE problem and was introduced by Lyubashevsky, Peikert and Regev [18].It is based on the hardness of distinguishing polynomial tuples (ai(x), bi(x)) where ai(x)

2Qubits can represent numerous possible combinations of 1s and 0s at the same time allowing to analyzea vast number of outcomes at the same time. The final result of a calculation is obtained after qubits aremeasured. Measuring them forces them to collapse to either 1 or 0.

3A pair of qubits are entangled when they exist in a single quantum state, a change in one of them willchange the other in a predictable way. This property will exponentially increase the computer’s calculationpower when incrementing the number of qubits.

4Most current symmetric cryptography and hash algorithms are considered relatively secure againstquantum computer attacks.

15

Page 17: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

are polynomials with coefficients chosen uniformly from Zq and bi(x) are of the formbi(x) = ai(x) · s(x) + ei(x) ∈ Rq where the secret polynomial s(x) and the error polyno-mials ei(x) ∈ Rq.

Module Learning With Errors: The Mod-LWE problem is the module version ofthe LWE problem analyzed by Langlois and Stehle [16]. It is based on the hardness ofdistinguishing uniform random samples of the form (a, u) ← U(Rlq × Rq) from the same

number of Mod-LWE samples (a, b = aT s + e) ∈ Rlq × Rq. Where s← βµ(Rlq) is a secret

vector fixed for all samples, a ← U(Rlq) are uniformly random vectors and e ← βµ(Rq)are small error terms sampled from an appropriate error distribution.

Module Learning With Rounding: The module version of LWR is an interpolatebetween LWR problem and its ring version. It reduces the complexity of LWR andintroduces protection against attacks to ring structures. This allows moving to highersecurity levels without changing the arithmetic. The Mod-LWR problem is based onthe hardness of distinguishing uniform samples from Mod-LWR samples of the form(a, b = bpq (aT s)e) ∈ Rl×1q ×Rp

2.3.3 Polynomial multiplication

Number-Theoretic Transform NTT is a tool that allows fast polynomial multipli-cation by performing c = NTT−1(NTT (a) ◦ NTT (b)) for a,b, c ∈ R. NTT can beimplemented very efficiently if for Rq = Zq[X]/(Xn + 1), n is a power of two and q isprime.

Karatsuba Karatsuba multiplication method consists of a top-down recursive approach,large polynomial multiplications are recursively split into smaller ones until a thresholdis reached. At this point, a quadratic-complexity polynomial multiplication method isapplied.

Toom-Cook Toom-Cook multiplication method is a generalization of the Karatsubamethod, it can be used to split an initial large polynomial multiplication into smaller onesand after that apply the Karatsuba method to an already reduced polynomial.

2.3.4 Lattice-based KEM schemes

Lattice-based cryptography is one of the most promising candidates to post-quantumcryptography standardization, as it is resistant to all known quantum attacks. This projectwill integrate several lattice-based Key Encapsulation Mechanisms into mbedtls. All ofthem, with their own particularities, follow the same workflow. Firstly, the server, usingthe Key Generation function, generates the public matrix A, the secret vector s, whichbecomes the secret key (sk), and sends to the client the multiplication of the publicmatrix with the secret vector and a small error (b = As + e) together with the seed usedto generate A creating the public-key (pk). The client then generates A, s’ and obtainsb’ = As’ + e. It generates v′ = bT s’ and adds the 256 bit key m to it, from this andb′ it obtains the ciphertext c. From hashing the server’s pk, the 256 bit key m and c itobtains the shared key K. The client then transmits c := (cm,b’) to the server. Theserver generates v = b’s and obtains m′ from m′ = v − cm. Finally it gets the sharedkey K by hashing pk, m′ and c. In Figure 2.6 there is a graphical representation of theexplanation given above.

16

Page 18: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Server Client

Generate public matrix AGenerate secret vector s

return pk := (b, seedA), sk := spk

Generate AGenerate s’b’ = As’ + ev′ = bT s’cm = v′ +mc := (cm,b’)K = Hash(pk,m, c)c

v = b’sm′ = v − cm

K = Hash(pk,m′, c)

KeyGen

Encaps

Decaps

Figure 2.6: Key Encapsulation Mechanism

Unlike with classical KEM schemes such as RSA or DDH, two parties using post-quantum KEM schemes sometimes fail to agree on the same key, meaning with theseschemes there is a small scope for errors. Algorithm designers try to mitigate these errorsas much as possible. Parameters of KEM schemes, specifically A and s, will be generateddifferently according to each algorithm. They can be standard lattice (Frodo [4]), modulelattice (Saber, Kyber), or ideal lattice (NewHope). We will explain this with further detailin the following chapter where all implemented algorithms will be introduced.

2.3.5 Lattice-based digital signatures

Digital signatures based on the hardness of lattice problems can be classified so far intothree different categories, GGH/NTRUSign signatures [15] [21], hash-and-sign signatures,whose paradigm follows the seminal work by Diffie and Hellman, and Fiat-Shamir signa-tures [13]. As this project has only introduced Dilithium post-quantum digital signature,this section will focus only on Fiat-Shamir kind of signatures, category in which we canfind the implemented post-quantum signature.

2.3.5.1 Fiat-Shamir signatures

This section will present an overview of how Fiat-Shamir signature schemes work. Asmentioned in Section 2.2.3, digital signature schemes are formed by three functions: keygeneration, signature and verify. In Figure 2.7 there is a graphical representation of thefunctions explained below.

• Key generation: First of all, the public matrix A and the random secret vectorss1 and s2 are generated. Then t, which belongs to the public-key, is generatedfrom the public matrix and secret vectors. The key generation function returns thepublic and secret keys. The public-key will be sent to the verifier, in TLS protocol itwill be transmitted in the certificate, and the secret key will be used in the signingalgorithm.

17

Page 19: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

• Sign: To begin with, the signer generates the masking vector y and computes w1

from the high-order bits of Ay. Next, it obtains the challenge c from hashing themessage M and w1. The signature z is computed from y, c and s1. Although z couldalready work as the signature, in order to avoid the direct dependency between thesignature and the secret vector, rejection sampling will be applied to z. Finally, thefunction returns the sampled signature together with the challenge, and this will besent to the verifier with the message.

• Verify: The verifier obtains w′1 from the high-order bits of Az − ct. If c and thehashing function applied to M and w′1 are the same, and it can be verified thatrejection sampling was correctly implemented in z, the signature is correct.

Signer Verifier

KeyGenGenerate public matrix AGenerate secret vectors (s1, s2)t := As1 + s2return pk := (A, t), sk := (A, t, s1, s2)

sk

M

SignGenerate masking vector yw1 = HighBits(Ay)c = Hash(M,w1)z = y + cs1Rejection sampling on zreturn σ := (z, c)

M,pk, σ

Verifyw′1 = HighBits(Az− ct)Check rejection samplingCompare c and Hash(M ||w′1)

Figure 2.7: Digital Signature

18

Page 20: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Chapter 3

KEM integration into mbedtls

This chapter will introduce how the integration of KEM post-quantum schemes intombedtls library has been performed. It will also include an explanation of all the im-plemented algorithms.

3.1 Integration procedure

This section will provide a generic explanation of how the integration of all post-quantumKEM schemes has been performed. Details about the integrated algorithms will be givenin Section 3.2. The reference implementation source code of each algorithm has beenincluded inside the mbedtls library and each of the integrated algorithms can be activatedseparately in the mbedtls config.h file. The specific defines for each algorithm will also beexplained in Section 3.2.

3.1.1 Cipher suites

As explained in Section 2.1.2, TLS decides upon the type of key exchange, symmetricencryption and message authentication by choosing a certain cipher suite. For this reason,to integrate post-quantum KEM schemes into mbedtls new cipher suites have been created,one for each of the introduced algorithms:

• MBEDTLS TLS SABER DILITHIUM WITH AES 256 GCM SHA256

• MBEDTLS TLS KYBER DILITHIUM WITH AES 256 GCM SHA256

• MBEDTLS TLS NEWHOPE DILITHIUM WITH AES 256 GCM SHA256

We will later explain the specifics for each scheme, but now the common characteristicsof all of them will be described.

• Mode for symmetric encryption: AES-256 in GCM mode [20]. AES-256 was chosenas the symmetric encryption cipher as, due to the length of its key, it is consideredto be quantum-safe. Quantum computers are able to reduce brute force attacks timeto its square root by using Grover’s search[14], therefore, if AES-128 was to be used,the attack time would be reduced to 264 which is not considered secure. By usingAES-256 instead, the attack time is reduced to 2128 which is still considered secure.In addition, GCM mode was chosen due to its efficiency and the fact that it providesboth privacy and integrity.

19

Page 21: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

• Mode for message authentication: SHA-256 [22]. It was chosen because, as it hasbecome the standard, it will minimize the possibilities of encountering incompatibil-ities.

• Mode for key exchange: Post-quantum KEM schemes have been used as Key Ex-changes in the mbedtls library. The next section will explain this with further detail.

• Signature algorithm: All the created cipher suites use the post-quantum newly in-tegrated signature scheme, Dilithium. The integration of this algorithm will beexplained in the following chapter.

3.1.2 Key exchange

Key exchange is defined as the procedure by which two parties exchange cryptographickeys. To ease the integration of post-quantum cryptography in mbedtls, KEM post-quantum algorithms will be used as Key encapsulation mechanisms inside the mbedtlslibrary. In the following subsections, common properties of all the KEM schemes used askey exchanges and their related functions will be explained.

3.1.2.1 Key exchange characteristics

The defined key exchanges use server certificate and allow client certificate requests. Con-sequently, they allow server and client authentication. The mbedtls library, however, hasnot yet implemented client side authentication. They also involve server signature, thissignature will use a post-quantum algorithm whose integration is explained in the nextchapter. Finally, they include the use of a pre-shared secret. The pre-shared secret hasan important role in the introduction of KEM post-quantum schemes into mbedtls. Thekeys for encryption of the application data are obtained from what is called the MasterSecret. This Master Secret is derived from the random numbers of both client and serverand, if it is present, also from the pre-shared secret. In Section 3.1.3 the changes made tointroduce post-quantum schemes in this procedure will be explained.

3.1.2.2 Key exchange related functions

To ease the integration of post-quantum KEM as key exchanges, new files for each imple-mented algorithm have been created. They contain a series of auxiliary functions that willbe called from the TLS handshake as well as a context containing all necessary variablesfor KEM schemes integration that will be introduced inside the handshake parametersdefinition. Although each file is used for a different algorithm they all have a commonstructure of functions and variables. For each algorithm, the name of the defined contextand functions will vary, to avoid repetitive code we will use PQKEMscheme where thename of the algorithm should be placed.To provide a better understanding of the functions, the variable definition will be in-troduced first. Following the design criteria of the mbedtls library, all KEM schemesrelated variables are defined inside a struct known as context, as can be seen in the SourceCode 3.1. The constants used to set the context’s arrays sizes are defined in each algorithmpackage.

1 typedef struct mbedtls_PQKEMscheme_context

2 {

3 uint8_t pk[CRYPTO_PUBLICKEYBYTES ];

4 uint8_t sk[CRYPTO_SECRETKEYBYTES ];

5 uint8_t ct[CRYPTO_CIPHERTEXTBYTES ];

20

Page 22: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

6 uint8_t ss[CRYPTO_BYTES ];

7 unsigned char entropy_input [48];

8 }

Source code 3.1: Post-quantum KEM context

Next, you will find all the functions source code together with a short explanationof their purpose. To begin with, the initialization function shown in Source Code 3.2allocates memory for each element of the given context.

1 int mbedtls_PQKEMscheme_init(mbedtls_PQKEMscheme_context *ctx){

2 memset(ctx ->pk, 0, CRYPTO_PUBLICKEYBYTES);

3 memset(ctx ->sk, 0, CRYPTO_SECRETKEYBYTES);

4 memset(ctx ->ct, 0, CRYPTO_CIPHERTEXTBYTES);

5 memset(ctx ->ss, 0, CRYPTO_BYTES);

6 memset(ctx ->pk, 0, 48);

7 }

Source code 3.2: Initialization function

In the Source Code 3.3 we find the function that generates the server public and privatekeys. For the key generation, it calls a function defined in each algorithm package, whichgenerates the public-private key pair and places the result in the given arrays. The calledfunction follows the structure explained in Section 2.3.4 KeyGen function.

1 int mbedtls_PQKEMscheme_make_pk_sk(mbedtls_PQKEMscheme_context *ctx , size_t

*olen , unsigned char *buf){

2 // Initialize the random number generator

3 uint64_t i;

4 for (i=0; i<48; i++)

5 ctx ->entropy_input[i] = i;

6 randombytes_init(ctx ->entropy_input , NULL , 256);

7

8 // Generate the server public and secret keys

9 crypto_kem_keypair(ctx ->pk, ctx ->sk);

10

11 // Write the public -key to the buffer

12 for(i=0; i<CRYPTO_PUBLICKEYBYTES; i++){

13 buf[i] = (unsigned char) ctx ->pk[i];

14 }

15

16 // Update the output length and the buffer pointer

17 *olen = CRYPTO_PUBLICKEYBYTES;

18 buf += CRYPTO_PUBLICKEYBYTES;

19

20 return (0);

21 }

Source code 3.3: Key generation function

The created files will also provide a function that, given a buffer containing the serverpublic-key, sets the corresponding value in the given context. This function is shown inSource Code 3.4.

1 int mbedtls_PQKEMscheme_parse_pk(mbedtls_PQKEMscheme_context *ctx , unsigned

char *buf){

2

3 memcpy(ctx ->pk, *buf , CRYPTO_PUBLICKEYBYTES);

4 *buf += CRYPTO_PUBLICKEYBYTES;

5

6 return (0);

21

Page 23: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

7 }

Source code 3.4: Public-key obtention function

Once the client has been able to obtain the server public-key, it will generate theshared secret as well as a ciphertext to send to the server. The code that provides thisfunctionality is shown in the Source Code 3.5. The generation will be done calling afunction defined in each algorithm package which, given a server public-key, producesboth the shared secret and the ciphertext. This function follows the scheme described inSection 2.3.4 Encaps function.

1 int mbedtls_PQKEMscheme_make_ct_ss(mbedtls_PQKEMscheme_context *ctx , size_t

*olen , unsigned char *buf){

2

3 // Obtain ciphertext and shared secret from server ’s pk

4 crypto_kem_enc(ctx ->ct, ctx ->ss, ctx ->pk);

5

6 // Write the ciphertext to the output buffer

7 for(int i = 0; i<CRYPTO_CIPHERTEXTBYTES; i++){

8 buf[i] = (unsigned char) ctx ->ct[i];

9 }

10

11 // Update the output length

12 *olen = CRYPTO_CIPHERTEXTBYTES;

13

14

15 return (0);

16 }

Source code 3.5: Shared secret and ciphertext generation function

Finally, as can be seen in the Source Code 3.6, once the server has received theciphertext from the client he will use his secret key to decrypt it and obtain the sharedsecret. Once again, the function will be using a function from each algorithm packagewhich, given the ciphertext and the server secret key, obtains the shared secret. Thisfunction follows the scheme of the Decaps function explained in Section 2.3.4.

1 int mbedtls_PQKEMscheme_get_ss(mbedtls_PQKEMscheme_context *ctx , const

unsigned char *buf){

2

3 // Obtain shared secret from server ’s sk and ciphertext

4 crypto_kem_dec(ctx ->ss, buf , ctx ->sk);

5

6 return (0);

7 }

Source code 3.6: Shared secret obtention function

3.1.3 Modifications at the TLS handshake

This section will introduce the modifications performed in the TLS handshake which isexplained in Section 2.1.2. First of all, the cipher suite of the desired algorithm is set asthe first in the order of preference to force client and server to agree upon it. Next, as thehandshake procedure in the mbedtls library is divided into steps that represent each of themessages exchanged, some of them will be modified to introduce the post-quantum KEMschemes. Those corresponding to ServerKeyExchage and the ClientKeyExchange are theones to be altered. In addition, the value of the pre-shared key (also known as premaster

22

Page 24: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

secret) will be also modified. We will introduce some source codes to better understandthe given explanation. Once again, as all algorithms follow the same structure, we will usePQKEMscheme where the name of the KEM scheme should go to avoid repetitive code.

• Server Key Exchange: the ServerKeyExchange message will be modified to handlethe integrated KEM schemes. It will change in both client and server:

– Server side: See in Source Code 3.7. The algorithms contexts will be initializedusing the function defined in the Source Code 3.2. Then, the generation ofprivate-public key pair will take place by calling the function introduced inSource Code 3.3. Finally the public-key will be sent to the client inside thehandshake message.

– Client side: See Source Code 3.8. The parsing of the ServerKeyExchange mes-sage will have to add the post-quantum KEM schemes cases. The functiondefined in the Source Code 3.4 will be used to add the server public-key to thealgorithm context.

• Client Key Exchange: the ClientKeyExchange message will also be modified to in-troduce the post-quantum KEM schemes key exchange cases. Both client and serversides will be altered:

– Client side: See Source Code 3.9. As the client is already in possession of theserver’s public-key it will call the function in Source Code 3.5 to generate theshared secret and the ciphertext. It will then send the ciphertext to the serverinside the handshake message.

– Server side: The parsing for the post-quantum algorithms cases will be intro-duced. From the ClientKeyExchange message the server will obtain the cipher-text generated by the client. It will then call the function defined in SourceCode 3.6 with which, using its secret key, it will decrypt the ciphertext andobtain the shared secret.

• Master secret: See Source code 3.11 for changes in the client side and 3.10 forthe server side. After the ServerKeyExchange and ClientKeyExchange messagesboth client and server are in possession of the post-quantum KEM schemes sharedsecret and, by using this shared key, they will generate secure encryption keys forapplication data exchange. As was explained in Section 3.1.2, the Master Secretis the origin of all the keys used to encrypt application data. This Master Secretis generated using the client and server randoms (obtained in the ServerHello andClientHello messages) and the premaster secret (if there is one). For this reason, inorder to provide secure symmetric keys to exchange application data, it was decidedto set the post-quantum KEM schemes shared secret as the premaster secret. Thisway, a post-quantum secure key is used to generate the symmetric keys creating aquantum-secure communication. The premaster secret size is a parameter that canbe chosen when defining a new key exchange. When we integrated post-quantumKEM schemes as key exchanges, the size of the pre-master secret was defined to bethe same as the KEM shared secret size.

1 #if defined(MBEDTLS_KEY_EXCHANGE_PQKEMscheme_ENABLED)

2 if(mbedtls_ssl_ciphersuite_uses_PQKEMscheme(ciphersuite_info)){

3 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;

4 size_t len = 0;

5 mbedtls_PQKEMscheme_init (&ssl ->handshake ->PQKEMscheme_ctx);

23

Page 25: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

6

7 if( ( ret = mbedtls_PQKEMscheme_make_pk_sk(

8 &ssl ->handshake ->PQKEMscheme_ctx , &len ,

9 ssl ->out_msg + ssl ->out_msglen) ) != 0 )

10 {

11 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_PQKEMscheme_make_pk_sk", ret

);

12 return( ret );

13 }

14 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)

15 dig_signed = ssl ->out_msg + ssl ->out_msglen;

16 #endif

17 ssl ->out_msglen += len;

18

19 }

20 #endif /* MBEDTLS_KEY_EXCHANGE_PQKEMscheme */

Source code 3.7: Server Key Exchange, server side

1 #if defined(MBEDTLS_KEY_EXCHANGE_PQKEMscheme_ENABLED)

2 if( ciphersuite_info ->key_exchange == MBEDTLS_KEY_EXCHANGE_PQKEMscheme)

{

3 mbedtls_PQKEMscheme_init (&ssl ->handshake ->PQKEMscheme_ctx);

4 ret = mbedtls_PQKEMscheme_parse_pk (&ssl ->handshake ->PQKEMscheme_ctx

, p);

5 if(ret !=0){

6 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_PQKEMscheme_parse_pk", ret );

7 return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );

8 }

9

10 }

11 else

12 #endif /* MBEDTLS_KEY_EXCHANGE_PQKEMscheme_ENABLED */

Source code 3.8: Server Key Exchange, client side

1 #if defined(MBEDTLS_KEY_EXCHANGE_PQKEMscheme_ENABLED)

2 if( ciphersuite_info ->key_exchange == MBEDTLS_KEY_EXCHANGE_PQKEMscheme)

3 {

4 header_len = 4;

5

6 ret = mbedtls_PQKEMscheme_make_ct_ss (&ssl ->handshake ->

PQKEMscheme_ctx , &content_len , &ssl ->out_msg[header_len ]);

7

8 if( ret != 0 )

9 {

10 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_PQKEMscheme_make_ct_ss", ret

);

11 return( ret );

12 }

13 }

14 else

15 #endif /* MBEDTLS_KEY_EXCHANGE_PQKEMscheme_ENABLED */

Source code 3.9: Client Key Exchange, client side

1 #if defined(MBEDTLS_KEY_EXCHANGE_PQKEMscheme_ENABLED)

2 if(ciphersuite_info ->key_exchange == MBEDTLS_KEY_EXCHANGE_PQKEMscheme)

3 {

4 ret = mbedtls_PQKEMscheme_get_ss (&ssl ->handshake ->PQKEMscheme_ctx ,

p);

24

Page 26: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

5

6 if(ret != 0)

7 {

8 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_PQKEMscheme_get_ss", ret );

9 return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );

10 }

11 //Set PQKEMscheme shared secret as premaster key

12 for(int i = 0; i<CRYPTO_BYTES; i++){

13 ssl ->handshake ->premaster[i] = ssl ->handshake ->PQKEMscheme_ctx.

ss[i];

14 }

15

16 ssl ->handshake ->pmslen = CRYPTO_BYTES;

17 }

18 else

19 #endif /* MBEDTLS_KEY_EXCHANGE_PQKEMscheme_ENABLED */

Source code 3.10: Client Key Exchange, server side

1 #if defined(MBEDTLS_KEY_EXCHANGE_PQKEMscheme_ENABLED)

2 //Set PQKEMscheme shared secret as premaster key

3 if(ciphersuite_info ->id ==

MBEDTLS_TLS_PQKEMscheme_WITH_AES_256_GCM_SHA256){

4 for(int i = 0; i<CRYPTO_BYTES; i++){

5 ssl ->handshake ->premaster[i] = ssl ->handshake ->PQKEMscheme_ctx.

ss[i];

6 }

7 ssl ->handshake ->pmslen = CRYPTO_BYTES;

8 }

9 #endif /* MBEDTLS_KEY_EXCHANGE_PQKEMscheme_ENABLED */

Source code 3.11: Premaster secret, client side

3.2 Post-quantum KEM schemes

The general structure of a lattice-based KEM scheme was explained in Section 2.6, thissection aims to complete the given information by introducing specific details of each ofthe implemented schemes, all of them are candidates of NIST standardization competition.

3.2.1 Saber

Saber[12] is a post-quantum KEM scheme whose security relies on the hardness of theModule Learning with Rounding (Mod-LWR) problem. It is designed following three mainprinciples: simplicity of scheme and implementation, efficiency and flexibility. All integermoduli are chosen to be powers of 2. This choice contributes to simplicity but prevents theuse of NTT (number theoretic transform) to speed up polynomial multiplication. Saberuses a combination of Karatsuba and Toom-Cook methods instead.In order to activate Saber cryptographic primitives in mbedtls MBEDTLS SABER C defineshould be used. And the Saber cipher suite is activated using MBEDTLS KEY EXCHANGE-

SABER DILITHIUM ENABLED define.

3.2.2 Kyber

Kyber[5] algorithm, which is part of the Cryptographic Suite for Algebraic Lattices (CRYS-TALS), is built on the hardness of the Module-LWE (Mod-LWE) problem. It uses a square

25

Page 27: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

k× k matrix of polynomials in Rq as the public information, introducing simplicity in im-plementation as in order to change the security level, it is only required to change thedimensions of the matrix. It uses NTT to speed up polynomial multiplication.To activate Kyber cryptographic primitives in mbedtls MBEDTLS KYBER C define shouldbe used. Kyber cipher suite is activated using MBEDTLS KEY EXCHANGE KYBER DILITHIUM-

ENABLED define.

3.2.3 NewHope

NewHope[2] is a Key Encapsulation Mechanism protocol based on the Ring-LWE problem,it corrects errors, however, two or four coefficients at a time instead of one, as it happenedwith other KEM based on this problem. In this algorithm, error vectors are sampled froma Binomial distribution not from a Gaussian distribution due to difficulties when tryingto implement and efficient and protected against timing attacks Gaussian sampler. It alsouses NTT to speed up polynomial multiplication.To activate NewHope cryptographic primitives in mbedtls MBEDTLS NEWHOPE C define shouldbe used. NewHope cipher suite is activated using MBEDTLS KEY EXCHANGE NEWHOPE DILI-

THIUM ENABLED

26

Page 28: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Chapter 4

Digital signature integration intombedtls

This chapter will provide an explanation of how the integration of post-quantum digitalsignature into the mbedtls library has been performed. It will also include an overview ofthe implemented algorithm.

4.1 Integration procedure

This part of the project had as an objective the integration of post-quantum digital sig-natures into mbedtls. As was explained in Section 2.1.1, it is the TLS handshake modifi-cation that will allow the integration of post-quantum algorithms. More precisely, digitalsignatures inside the mbedtls library can be found in the used certificates as well as inthe ServerKeyExchange message. To enable the post-quantum signature that will be ex-plained in this section, it is important to make sure that the key-exchanges that use ithave server signature enabled. It is also necessary to add the signature case to functionsof ssl tls.c file that allows the obtention of the signature algorithm known the public-keyalgorithm and the other way around.To perform post-quantum digital signatures integration, the source code of the signaturesis included into mbedtls but they can be activated separately inside the config.h file, thespecific define will be provided in Section 4.2. Although this project has only implementedone post-quantum signature algorithm so far, the procedure explained in this section canbe generically applied for all latice-based digital signatures. Details about Dilithium [10],the integrated algorithm, will be given in Section 4.2.

4.1.1 Message digest

As was explained in Section 2.2.3, digital signatures provide message authentication, dataintegrity and non-repudiation. Message digests are used by digital signatures to ensure theintegrity of a message sent over an insecure channel. By means of a one-way hash function,the sender creates an image of the message called digest. The message and the digest aresent to the receiver who, using the same hash function as the sender, computes the digestfrom the message. If the digests are equal the integrity of the message is confirmed. Section4.1.2 will explain how digests are later encrypted with the sender’s private-key to providenot only integrity but also authenticity.SHAKE256 is a hash algorithm that belongs to the latest member of the secure hashalgorithm family of standards, SHA-3 [11]. It is the hash algorithm used by the integrated

27

Page 29: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

post-quantum signature in the mode of operation chosen for this project. This sectionwill explain the integration of SHAKE256 as message digest to be used by post-quantumdigital signatures. The process followed to perform this integration could be extrapolatedto integrate other members of the SHA-3 family that might be used by other signaturealgorithms.

4.1.1.1 Message digests in mbedtls

In the mbedtls library, message digests are wrapped inside md.c, a file with generic func-tions that allows the mbedtls library to use message digest functions the same way inde-pendently of the hash they work with. Next, the modifications done in md.c in order tointegrate SHAKE256 message digest will be explained. The source code for the SHAKE256hash function is provided in the post-quantum signature library.First of all, the information for each specific hash is defined. All of them follow the struc-ture shown in Source Code 4.1, and the chosen parameters for SHAKE256 are the ones inSource Code 4.2. The block length is given by the hash source code and the output lengthwas chosen because of the security levels of SHAKE256:

• Collision resistance = min(output lenght/2, 256) bits

• Preimage resistance = min(output length, 256) bits

• Second preimage resistance = min(output length, 256) bits

As shown above, the minimum output length needed to obtain the maximum security levelis 512 bits (64 bytes).

1 struct mbedtls_md_info_t

2 {

3 /** Name of the message digest */

4 const char * name;

5

6 /** Digest identifier */

7 mbedtls_md_type_t type;

8

9 /** Output length of the digest function in bytes */

10 unsigned char size;

11

12

13 /** Block length of the digest function in bytes */

14 unsigned char block_size;

15 };

Source code 4.1: Message digest information

1 const mbedtls_md_info_t mbedtls_shake256_info = {

2 "SHAKE256",

3 MBEDTLS_MD_SHAKE256 ,

4 64,

5 136,

6 };

Source code 4.2: SHAKE256 information

After having defined SHAKE256 information, the new message digest will be alsointroduced in all functions of md.c needed by the signature algorithms. These functionsare generic and their main purpose is to call specific message digest functions definedinside each message digest file. Therefore, we consider that the explanation given inSection 4.1.1.2 is enough to understand the functions that need to be modified.

28

Page 30: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

4.1.1.2 SHAKE256 message digest

To properly integrate the chosen post-quantum digital signature into mbedtls a messagedigest that uses SHAKE256 hash has been created, this section will provide an overview ofits parameters and functions. As mentioned in the previous section, the source code of thehash functions is provided inside the signature library, some of them will be called fromthe created message digest to perform hash functionalities. All the functions explainedbelow are defined inside the new file, shake256.c.Firstly, a SHAKE256 context as shown in Source Code 4.3 is defined. The context allowsto store data at intermediate stages of the digest process and it contains the state variableneeded by the hash functions.

1 typedef struct mbedtls_shake256_context

2 {

3 keccak_state state; /*!< The intermediate digest state. */

4 unsigned char *buffer; /*!< The data block being processed. */

5 uint32_t buff_len; /*!< The amount of data that has been added to

buffer. */

6 }

7 mbedtls_shake256_context;

Source code 4.3: SHAKE256 context

Initialization and free functions as the ones shown in source codes 4.4 and 4.5 are alsoneeded.

1 void mbedtls_shake256_init( mbedtls_shake256_context *ctx )

2 {

3 memset( ctx , 0, sizeof( mbedtls_shake256_context ) );

4 }

Source code 4.4: SHAKE256 init

1 void mbedtls_shake256_free( mbedtls_shake256_context *ctx )

2 {

3 if( ctx == NULL )

4 return;

5

6 mbedtls_platform_zeroize( ctx , sizeof( mbedtls_shake256_context ) );

7 }

Source code 4.5: SHAKE256 free

The start function shown in Source Code 4.6 sets the processed length to 0 ensuringthat subsequent calls to update function do not mix data with previous message digestusages.

1 /*

2 * SHAKE -256 context setup

3 */

4 int mbedtls_shake256_starts_ret( mbedtls_shake256_context *ctx)

5 {

6 ctx ->buff_len = 0;

7 return( 0 );

8 }

Source code 4.6: SHAKE256 start

In Source Code 4.7 the update function of the message digest can be found. It storesdata in the context buffer to allow its later hashing. It can be called multiple times beforecalling the finish function to perform the final digest.

29

Page 31: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

1 /*

2 * SHAKE -256 process buffer

3 */

4 int mbedtls_shake256_update_ret( mbedtls_shake256_context *ctx ,

5 const unsigned char *input ,

6 size_t ilen )

7 {

8 *(&ctx ->buffer + ctx ->buff_len) = (unsigned char *) malloc(ilen);

9 memcpy(ctx ->buffer + ctx ->buff_len , input , ilen);

10 ctx ->buff_len += ilen;

11 return (0);

12 }

Source code 4.7: SHAKE256 update

The finish function of Source Code 4.8 performs the final digest by calling the hashfunction on the stored data of the context. It returns the hash ready to be signed.

1 /*

2 * SHAKE -256 final digest

3 */

4 int mbedtls_shake256_finish_ret( mbedtls_shake256_context *ctx ,

5 unsigned char output [64] )

6 {

7 shake256_dilithium(output , 64, ctx ->buffer , (unsigned long long) ctx ->

buff_len);

8 return( 0 );

9 }

Source code 4.8: SHAKE256 finish

The function in Source Code 4.9 allows to perform the SHAKE256 hash on the giveninput.

1 /*

2 * output = SHAKE -256( input buffer )

3 */

4 int mbedtls_shake256_ret( const unsigned char *input ,

5 size_t ilen ,

6 unsigned char *output)

7 {

8

9 shake256_dilithium(output , 64, input , (unsigned long long) ilen);

10 return( 0 );

11 }

Source code 4.9: SHAKE256

4.1.2 Signature algorithm

Once the hash function needed by the chosen post-quantum signature algorithm has beenintegrated into a message digest, the signature algorithm can also be deployed insidethe mbedtls library. This section will first explain how digital signature algorithms areimplemented in the mbedtls library and provide some guidelines on the code that needsto be added to integrate a new signature algorithm. Afterwards, it will introduce thestructure of the post-quantum signature file created to ease the implementation of the post-quantum signature in mbedlts. As mentioned before, although the signature algorithmthat appears in the explanation that follows is Dilithium, the procedure explained can alsobe applied for other algorithms integration.

30

Page 32: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

4.1.2.1 Signature algorithms in mbedtls

Digital signature algorithms are implemented in the mbedtls library by defining a contextwhich includes, not only the kind of algorithm, but also a pointer to the all the functions ofdigital signatures that might be needed throughout the rest of the library. These contextand functions are defined inside the pk wrap.c file and pk.c file will be the one to take careof calling the appropriate context depending on the chosen algorithm. Next, the contextdefined for Dilithium post-quantum signature will be explained. As the functions pointedby the context are mainly calls to other functions defined inside the post-quantum signa-ture file, which is explained in Section 4.1.2.2, this section will provide a brief explanationof all of them but their source code will not be included. The functions explained beloware the ones pointed by the context defined in Source Code 4.10.

• dilithium get bitlen: Provides Dilithium public-key size in bits.

• dilithium can do: Returns true if the given context implements Dilithium public-key type.

• dilithium verify wrap: Checks the correctness of a dilithium signature.

• dilithium sign wrap: Computes a Dilithium signature.

• dilithium check pair: Checks if the public keys of the two given contexts areequal.

• dilithium alloc wrap: Creates a Dilithium context and initializes it.

• dilithium free wrap: Frees the given context.

1 const mbedtls_pk_info_t mbedtls_dilithium_info = {

2 MBEDTLS_PK_DILITHIUM , /* Public -key type */

3 "DILITHIUM", /* Type name */

4 dilithium_get_bitlen ,

5 dilithium_can_do ,

6 dilithium_verify_wrap ,

7 dilithium_sign_wrap ,

8 NULL ,

9 NULL ,

10 dilithium_check_pair ,

11 dilithium_alloc_wrap ,

12 dilithium_free_wrap ,

13 NULL ,

14 };

Source code 4.10: Dilithium pk information

4.1.2.2 Dilithium signature algorithm

Following the structure of mbedtls library, dilithium.c and dilithium.h files were created.They wrap the functions and parameters of Dilithium post-quantum signature algorithmand will provide easier access to the signature source code.To begin with, a Dilithium context containing the private a public-key as shown in SourceCode 4.11 is created.

31

Page 33: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

1 typedef struct mbedtls_dilithium_context{

2 unsigned char pk[CRYPTO_PUBLICKEYBYTES ];

3 unsigned char sk[CRYPTO_SECRETKEYBYTES ];

4 }mbedtls_dilithium_context;

Source code 4.11: Dilithium context

Afterward, several functions which will be referenced from the mbedtls library aredefined. As the functions are mainly inner calls to other functions inside the Dilithiumsource code we will provide a brief explanation of each of them but not their source code.

• mbedtls dilithium get len: Returns the length of the Dilithium public-key.

• mbedtls dilithium read signature: Will call the function crypto sign open ofDilithium source code that reads and checks the provided signature.

• mbedtls dilithium write signature: Calls the Dilithium package crypto sign

function and performs the signature operation.

• mbedtls dilithium init:Initializes the given Dilithium context.

• mbedtls dilithium free: Frees the given Dilithium context.

4.1.3 Digital Certificates

Cryptographic certificates are electronic documents that allow to share and prove theownership of a public-key. Certificates can be self-signed or signed by a trusted third partycalled Certificate Authority (CA). The client and server test programs provided by thembedtls library work with embed certificates for testing purposes. The test server owns aserver certificate signed by a trusted CA as well as the CA certificate. It is also in possessionof the server key whose public part is distributed in the server certificate. The test clientalso possesses the CA certificate, which allows to verify the signature of the received servercertificate. The mbedtls library provides programs for certificate generation, in this projectthey have been modified and used to generate certificates with post-quantum signaturesthat have been later embedded into the server and client test programs. To perform suchmodification, Dilithium keyfiles, key parsing and writing functionalities that can handleDilithium case and Dilithium object identifiers are necessary. This section will provide anoverview of the modifications performed to fulfill such requirements and finally talk aboutthe certificate generation itself.

4.1.3.1 Key generation

Both server and CA certificates need a keyfile to be generated. As the goal is to integrateDilithium post-quantum signature, a Dilithium keyfile will have to be created. To accom-plish this, the ability to create base64 encoded keyfiles was added to the Dilithium sourcecode. The keyfile is created following a newly defined ASN.1 [7] structure for Dilithiumkeys. The generated code to provide the keyfile generation ability uses the ASN.1 andbase64 functions of the mbedtls library. In Source Code 4.12 there is the function that,given the private and public-key, writes to the provided buffer the ASN.1 formatted keysand base64 encoded. This buffer is ready to be written to a file in PEM format.

1 int prepare_dilithium_key_formtat(unsigned char *pk , unsigned char *sk ,

unsigned char *final_buf){

2

32

Page 34: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

3 /*

4 * DILITHIUM_key ::= SEQUENCE {

5 * SecretKey BIT STRING ,

6 * PublicKey BIT STRING

7 * }

8 */

9

10 unsigned char *buf , *c;

11 size_t len = 0;

12 size_t *final_buf_bytes_written;

13 buf = (unsigned char *) malloc (5000);

14

15 c = buf + 5000;

16

17 // Write keys to buffer in ASN.1 format

18 MBEDTLS_ASN1_CHK_ADD( len , mbedtls_asn1_write_bitstring (&c, buf , pk

, CRYPTO_PUBLICKEYBYTES *8));

19 MBEDTLS_ASN1_CHK_ADD( len , mbedtls_asn1_write_bitstring (&c, buf , sk

, CRYPTO_SECRETKEYBYTES *8));

20 MBEDTLS_ASN1_CHK_ADD( len , mbedtls_asn1_write_len( &c, buf , len ) )

;

21 MBEDTLS_ASN1_CHK_ADD( len , mbedtls_asn1_write_tag( &c, buf ,

MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) );

22

23 // Base64 encode the written buffer

24 size_t final_buf_size = 4*( len / 3 + ( len % 3 != 0 ));

25 final_buf_bytes_written = (size_t *) malloc (16);

26 mbedtls_base64_encode(final_buf , final_buf_size + 1,

final_buf_bytes_written , buf , len);

27

28 // Return num of bytes in buffer

29 return final_buf_bytes_written;

30 }

Source code 4.12: Dilithium keyfile generation

4.1.3.2 Key parsing and writing

As explained at the beginning of this section, certificates allow to distribute server keys.This entails the need for key parsing and writing functions that can handle all supportedtypes of keys. Therefore, when adding the new post-quantum signature algorithm withits own key type these functions have to be modified. Keys can be present in keyfiles or inserver certificates. Due to the design choice for Dilithium key distribution, both privateand public Dilithium keys will be present in a keyfile and just the public one will appear inserver certificates. For this reason, a function to parse Dilithium public and private keyssequence, another to parse Dilithium public keys and finally a function to write publickeys are needed. Source codes 4.13, 4.14 and 4.15 show how these functions are defined.They all use the ASN.1 format and are included inside the pkparse.c and pkwrite.c filesof the mbedtls library.

1 static int pk_parse_key_dilithium(mbedtls_dilithium_context *pk, unsigned

char *key , size_t keylen){

2 int ret;

3 size_t len;

4 unsigned char *p = (unsigned char *) key;

5 unsigned char *end = p + keylen;

6

7 /*

33

Page 35: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

8 * DILITHIUM_key ::= SEQUENCE {

9 * SecretKey BIT STRING ,

10 * PublicKey BIT STRING

11 * }

12 */

13 if( ( ret = mbedtls_asn1_get_tag( &p, end , &len ,

14 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )

15 {

16 return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );

17 }

18

19 end = p + len;

20

21 if( ( ret = mbedtls_asn1_get_bitstring_null( &p, end , &len ) ) != 0 )

22 return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );

23

24 if( len != MBEDTLS_DILITHIUM_SK_LEN )

25 return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );

26

27 memcpy(pk->sk, p, len);

28

29 p += len;

30

31 if( ( ret = mbedtls_asn1_get_bitstring_null( &p, end , &len ) ) != 0 )

32 return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );

33

34 if( len != MBEDTLS_DILITHIUM_PK_LEN )

35 return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );

36

37 memcpy(pk->pk, p, len);

38

39 return (0);

40 }

Source code 4.13: Dilithium public and private-key parsing

1 static int pk_get_dilithiumpubkey( unsigned char **p, const unsigned char *

end , mbedtls_dilithium_context *dilithium )

2 {

3

4 /*

5 * PublicKey BIT STRING

6 */

7

8 if( ( ret = mbedtls_asn1_get_bitstring_null( &p, end , &len ) ) != 0 )

9 return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );

10

11 if( len != MBEDTLS_DILITHIUM_PK_LEN )

12 return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );

13

14 memcpy(dilithium ->pk, p, len);

15

16 p += len;

17

18 }

Source code 4.14: Dilithium public-key parsing

1 static int pk_write_dilithium_pubkey(unsigned char **p, unsigned char *

start , mbedtls_dilithium_context *dilithium ){

2

34

Page 36: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

3 size_t len = MBEDTLS_DILITHIUM_PK_LEN;

4

5 if( *p < start || (size_t)( *p - start ) < len )

6 return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );

7

8 MBEDTLS_ASN1_CHK_ADD( len , mbedtls_asn1_write_bitstring(p, start ,

dilithium ->pk , len *8));

9

10 return( (int) len );

11 }

Source code 4.15: Dilithium public-key writing

4.1.3.3 Object identifier

Object identifiers, also known as OIDs, are an identification mechanism standardizedby the International Telecommunications Union (ITU). In the mbedtls library they areused, between others, to identify the signature, message digest and key algorithms. Forthis reason, when adding a new post-quantum signature and a new message digest it isnecessary to create new object identifiers. After checking the standards the new objectidentifiers created for Dilithium and SHAKE256 are the ones shown in Source Code 4.16and Source Code 4.17.

1 /* id-dilithium -shake256 OBJECT IDENTIFIER ::= {

2 * joint -iso -ccitt (2) country (16) us (840) organization (1) gov (101) csor (3)

algorithms (4)

3 * id -dilithium -shake (3) 20 } */

4 #define MBEDTLS_OID_DILITHIUM_SHAKE256 MBEDTLS_OID_GOV "\x03\x04\x03\x14"

5

6 /* id-shake -256 OBJECT IDENTIFIER ::= { joint -iso -itu -t(2) country (16)

7 * us (840) organization (1) gov (101) csor (3) nistAlgorithm (4) hashAlgs (2)

8 * 12} } */

9 #define MBEDTLS_OID_SHAKE256 MBEDTLS_OID_GOV "\x03\x04\x02\x0c"

Source code 4.16: OIDs defines

1 // Signature algorithm OID

2 {

3 {ADD_LEN( MBEDTLS_OID_DILITHIUM_SHAKE256 ), "id -dilithium -shake256",

"Dilithium with SHAKE256"},

4 MBEDTLS_MD_SHAKE256 , MBEDTLS_PK_DILITHIUM ,

5 }

6

7 //Public -key OID

8 {

9 { ADD_LEN( MBEDTLS_OID_DILITHIUM_SHAKE256 ), "id -dilithium -shake256",

"Dilithium with SHAKE256" },

10 MBEDTLS_PK_DILITHIUM ,

11 }

12

13 // Message digest OID

14 {

15 { ADD_LEN( MBEDTLS_OID_SHAKE256 ), "id -shake -256", "SHAKE -256" },

16 MBEDTLS_MD_SHAKE256 ,

17 }

Source code 4.17: OIDs

35

Page 37: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

4.1.3.4 Certificate generation

After performing all the modifications explained above, certificates signed with the newpost-quantum signature algorithm can nearly be created. The last change that needsto be addressed is to add the signature hash algorithm to the certificate generation testprograms and the signature algorithm case to x509write files.With these final adjustments certificates can be created and embed into the test serverand client.

4.2 Post-quantum digital signature - Dilithium

Dilithium signature algorithm is a candidate for the NIST standardization competition andit is the only one that this project has implemented so far. It is based on an optimizedimplementation of the Fiat-Shamir approach explained in Section 2.3.5.1 and it relies onthe hardness of finding short vectors in lattices. The scheme uses both SHAKE128 andSHAKE256 hash functions within its implementation and it addresses polynomial multipli-cation using NTT. The novelty of Dilithium, when compared to other signature algorithmsis that it reduces the public-key size by a factor of 2.5 at the expense of increasing thesignature by around 150 bytes. Moreover, it applies uniform sampling to obtain random-ness, unlike other more compact lattice-based algorithms that require the generation ofsecret randomness from the discrete Gaussian distribution. Such generation is non-trivialand can easily end up in insecure implementations.In this project, Dilithium has been introduced to work with all three KEM schemes pre-sented in Section 3.2. As explained, each one of them can be activated separately using theprovided defines. In a similar way, the Dilithium signature can be activated in the config.hfile using the MBEDTLS DILITHIUM C define. To properly integrate Dilithium source codeinto mbedtls library and with the KEM schemes some function name changes have beenperformed to avoid conflicts.

36

Page 38: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Chapter 5

Performance evaluation

This chapter aims to provide a notion of the real-life practicality of the developed code.It will introduce the platform in which the code has been deployed and tested as well asthe results obtained in such tests. These results will be compared with measures takento classical cryptography algorithms, giving an overview of the possible advantages ordisadvantages of the switch towards post-quantum cryptography.

5.1 Platform deployment

The final goal of this project is to be able to establish a communication between a clientand a server using the TLS protocol and agreeing upon post-quantum KEM and signatureschemes. To be able to properly test and benchmark the developed code and obtain anotion of its application to real life, it will be deployed into a network created by twoRaspberry Pi 2 with a 100M Ethernet connection between them. Specifically, a LAN iscreated between the Raspberrys and a computer which also acts as the gateway to theinternet, necessary if a module needs to be installed into the boards.

5.1.1 Raspberry Pi 2 Model B

The Raspberry Pi is a small affordable computer created by the Raspberry Pi Foundation1

with educational purposes. From all the boards offered, Raspberry Pi 2 Model B wasthe one chosen for this project. It has a quad-core ARM Cortex-A7 processor running at900MHz and 1GB of RAM. It provides 100M ethernet network connection and it is capableof running multi-process operating system. This project will be using the Debian-basedLinux distribution Raspbian where it is possible to directly run the mbedtls library. Toallow time measurements, a module to enable CPU cycles count [19] was added to theboards. Additionally, the platform specific cycle counter code shown in Source Code 5.1was added to the mbedtls library.

1 uint32_t cpucycles(void)

2 {

3 uint32_t result;

4 __asm__ volatile("mrc p15 , 0, %0, c9 , c13 , 0":"=r" (result));

5 return result;

6 }

Source code 5.1: CPU cycle count

1https://www.raspberrypi.org/

37

Page 39: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

5.1.1.1 Modifications in the library

The integration of the post-quantum schemes into the mbedtls library has been performedworking as localhost on a computer. Consequently, when switching to the Raspberry LANinfrastructure, the changes to be performed are IP address related.The mbedtls library works with embed certificates for testing purposes. Server certificatescontain organization details, among them, the common name. To deploy the code on theRaspberrys, new certificates have to be generated in order to match the common namewith the static IP assigned to the board. To create them, the programs provided by thembedtls library are used. The server and client test programs need also to be modified towork with the static IPs of the boards instead of working with localhost.

5.2 Code performance evaluation

This section will introduce an evaluation of the implemented post-quantum primitives incomparison to classic cryptography. It will also expose the performance measure resultsof the TLS handshake for both post-quantum and classical cryptography. Time measureshave been taken with CPU cycles count and knowing that Raspberry Pi 2 clock works at900MHz. By using the linux taskset command it is possible to force the program to runin just one CPU and obtain an accurate time measurement. Some handshake messagesizes have also been measured, to obtain these sizes the messages have been evaluatedwith gdb2.All measures have been performed multiple times and, to provide a fair comparison, thesmallest results are the ones reported in this section.

5.2.1 Cryptographic primitives evaluation

This project has integrated both post-quantum KEM and signature schemes into thembedtls library. All post-quantum algorithms offer diverse implementations that allow tochange the security level. The chosen ones for this project are:

• Saber KEM scheme: Saber was chosen as the security level (level similar to AES-192).

• Kyber KEM scheme: Kyber-768 parameter set was chosen as the security level. Itis the level recommended by Kyber developers3. According to a very conservativeanalysis, it achieves more than 128 bits of security against all known classical andquantum attacks.

• NewHope KEM scheme: NewHope512-CCA-KEM is the security level chosen forthis project. It matches the brute-force security of AES-128.

• Dilithium signature scheme: Dilithium-1280x1024 is the level chosen for this project.It is the level recommended by the developers4 and according to a very conserva-tive analysis it achieves around 128 bits of security against all known classical andquantum attacks.

In order to provide a clearer vision of the influence of switching to post-quantum schemes,they will be compared with commonly used classic cryptography schemes. Specifically,

2https://www.gnu.org/software/gdb/3https://pq-crystals.org/kyber/index.shtml4https://pq-crystals.org/dilithium/

38

Page 40: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

KEM schemes will be compared to ECDHE (Elliptic-Curve Diphie Hellman Ephemeral)KEM scheme. Dilithium post-quantum signature algorithm, on the other hand, will becompared to ECDSA (Elliptic Curve Digital Signature Algorithm). Both ECDHE andECDSA are generated using the the SECP256R1 elliptic curve, which provides a 128-bit(classical) security level[6].

5.2.1.1 KEM schemes

Table 5.1 reports the measurements of Key Encapsulation Mechanism operations runtime.From the results, we can conclude that elliptic curve operations are costly for the targetplatforms and, in contrast, post-quantum schemes are pretty fast forward. Consequently,when targeting platforms of similar characteristics to Raspberry Pi 2 the switch fromclassical to post-quantum KEM schemes would imply a decrease in Key EncapsulationMechanism operations runtime.

KEM scheme Key Generation Encrypt Decrypt

Saber 2.7 ms 3.4 ms 3.7 msKyber 6.9 ms 8.5 ms 9 msNewHope 4.4 ms 6.8 ms 7 msECDHE 62.8 ms 290.1 ms 282.2 ms

Table 5.1: Runtime of KEM schemes operations

5.2.1.2 Signature algorithms

Table 5.2 shows the runtime of signature algorithms operations. As happened with KEMschemes, curve operations in signatures are also costly for the platform. The results showhow Dilithium post-quantum signature is two orders of magnitude faster than the classiccryptography algorithm. Once again, the transition to post-quantum schemes would resultin a considerable decrease in signature times.

Signature algorithm Key Generation Sign Verify

Dilithium 4.1 ms 2 ms 1.3 msECDSA 291.6 ms 301.7 ms 589.2 ms

Table 5.2: Runtime of digital signature operations

5.2.2 Handshake evaluation

Once the evaluation of the used cryptographic primitives has been performed, the wholeTLS handshake process can be analyzed with further insight. The performance of thenewly defined cipher suites explained in Section 3.1.1 will be compared to the classicalcryptography ciphersuite MBEDTLS TLS ECDHE ECDSA WITH AES 256 GCM SHA384. This ci-pher suite is based on elliptic curve cryptography and its KEM and signature algorithmsare the ones that have been analyzed in the previous section. The integration of post-quantum schemes does not only affect the handshake runtime, but also the size of someof the transmitted messages. Therefore, both these parameters will be submitted to eval-uation.

39

Page 41: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

5.2.2.1 Handshake runtime

Table 5.3 presents the results for the different cipher suites of handshake times in bothserver and client sides. The obtained results confirm the natural conclusion that could beobtained from measures in tables 5.1 and 5.2, that the handshake implementing classicalcryptography algorithms should be considerably slower than the ones with post-quantumcipher suites. Additionally, whereas in post-quantum cipher suites server side takes longerthan the client, in the implemented classical cipher suite it is the other way around. Thiscould be explained by the fact that, as shown in Table 5.2, while in Dilithium signaturekey generation and sign operations are slower than verify, in ECDSA signature verifyoperation is the costliest.

Cipher Suite Server Side Client side

SABER DILITHIUM 76 ms 58.9 msKYBER DILITHIUM 58.1 ms 48.5 msNEWHOPE DILITHIUM 57.8 ms 46.6 msECDHE ECDSA 899.1 ms 1782.2 ms

Table 5.3: Handshake runtime

5.2.2.2 Handshake message sizes

Finally, the impact of post-quantum schemes in handshake message sizes should be studied.The three handshake messages that are influenced by the switch of cryptography schemesare:

• Server Certificate: this project only works with server authentication. Therefore, un-like client certificates, server certificates will include the signature algorithm public-key and will be signed. Consequently, it will be affected by changes in signaturealgorithms.

• Server Key Exchange: this handshake message is used, between others, to transmitthe public-key to allow the Key-Exchange operation. Changes in KEM schemes willtherefore have an influence in this handshake message. Additionally, as mbedtlsworks with server authentication, this message will also include a signature.

• Client Key Exchange: this handshake message is used to transmit information neededby the server to finish the Key-Exchange. Consequently, changes in the KEM algo-rithm have an impact in Client Key Exchange size.

As can be seen in Table 5.4, post-quantum cipher suites messages are larger than theclassical cryptography ones. The reason for this increase is that, first of all, Dilithiumsignature keys, as well as the signature itself, are larger than ECDSA ones. In addition,post-quantum KEM public keys and ciphertexts, which are transmitted within the serverand client Key Exchange messages, have bigger sizes than ECDHE keys.The increase in message sizes has an impact on handshake times, as it affects messagetransmission speed. To obtain a notion of the real time increase this implies, we calculatethe time transmission difference between SABER DILITHIUM, the KEM scheme with a largertotal size, and ECDHE ECDSA. The global size difference between the two schemes is of12466B. Assuming the 100M network connection used in the deployment works at itsmaximum capacity, this would imply an increase of 1 ms in transmission time. Whencomparing this to the total handshake times shown in 5.3, the increase can be considered

40

Page 42: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

negligible. Were the library to be deployed in an infrastructure with a slower networkinterface, however, these calculations should be repeated to ensure the increase continuesto be negligible.

Cipher Suite ServerCertificate

Server KeyExchange

Client KeyExchange

SABER DILITHIUM 9059B 3761B 1092BKYBER DILITHIUM 9059B 3569B 740BNEWHOPE DILITHIUM 9059B 3697B 1124BECDHE ECDSA 1028B 280B 138B

Table 5.4: Handshake message sizes

41

Page 43: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Chapter 6

Conclusion and future work

6.1 Conclusion

This project has been developed with the intention of obtaining further insight into the vi-ability of evolving towards post-quantum cryptography. To this end, three KEM schemes(Saber, Kyber and NewHope) and a digital signature algorithm (Dilithium), all of themcandidates to the NIST post-quantum standardization competition, have been integratedinto mbedlts, an embedded TLS open source library. One of the issues faced by the switchto post-quantum cryptography is the increasing presence of embedded devices, which alsoneed to be secured, in our daily lives. For this reason, having successfully integrated thealgorithms into the mbedtls library, the resulting code was deployed into Raspberry Pi 2Model B.Performance time and message size measures were carried out in the embedded platform.Results were reported, not only from the post-quantum schemes, but also from a classicalcryptography algorithm to allow comparison. The results show how, when analyzing timeperformance, the implemented post-quantum algorithms overcome the classical ellipticcurve algorithms in all operations. Message sizes, on the other hand, are shorter whenusing classical cryptography. The difference, however, as is stated in the results Chapter,has a negligible performance impact when working with networks of similar characteristicsto the implemented one.The executed analysis leads to the conclusion, for the tested algorithms and similar plat-forms as the chosen one, that a switch towards post-quantum KEM and signature algo-rithms is not only feasible, but highly recommended.

6.2 Future work

6.2.1 Further algorithms integration

An effort is going on to develop quantum-resistant cryptographic protocols in anticipationof the arrival of quantum computers. As part of this process, NIST is carrying out astandardization competition to evolve towards post-quantum algorithms. This projecthas evaluated three KEM and one signature scheme so far. The future goal would be,however, to submit to evaluation all candidates of NIST procedure as is mandatory toensure that future post-quantum standards are valid for resource constrained devices.

42

Page 44: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

6.2.2 Optimized platform implementations

This project has focused on the provided portable C implementation of the chosen post-quantum algorithms, and it has been deployed directly in the operating system of anARM Cortex-A processor. Post-quantum algorithms, however, offer more specific platformimplementations, mostly targeting ARM Cortex-M processor, that take advantage of theplatform characteristics to speed up algorithms operations or optimize memory usage.These implementations should also be tested to analyze the improvements they introduceand their viability for real-life implementation.

43

Page 45: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

Bibliography

[1] Specification for the advanced encryption standard (aes). Federal Information Pro-cessing Standards Publication 197, 2001. http://csrc.nist.gov/publications/

fips/fips197/fips-197.pdf.

[2] Erdem Alkim, Leo Ducas, Thomas Poppelmann, and Peter Schwabe. Post-quantumkey exchange - a new hope. Cryptology ePrint Archive, Report 2015/1092, 2015.https://eprint.iacr.org/2015/1092.

[3] Abhishek Banerjee, Chris Peikert, and Alon Rosen. Pseudorandom functions and lat-tices. In David Pointcheval and Thomas Johansson, editors, Advances in Cryptology– EUROCRYPT 2012, pages 719–737, Berlin, Heidelberg, 2012. Springer Berlin Hei-delberg.

[4] Joppe Bos, Craig Costello, Leo Ducas, Ilya Mironov, Michael Naehrig, Valeria Niko-laenko, Ananth Raghunathan, and Douglas Stebila. Frodo: Take off the ring! prac-tical, quantum-secure key exchange from lwe. Cryptology ePrint Archive, Report2016/659, 2016. https://eprint.iacr.org/2016/659.

[5] Joppe Bos, Leo Ducas, Eike Kiltz, Tancrede Lepoint, Vadim Lyubashevsky, John M.Schanck, Peter Schwabe, Gregor Seiler, and Damien Stehle. Crystals – kyber: a cca-secure module-lattice-based kem. Cryptology ePrint Archive, Report 2017/634, 2017.https://eprint.iacr.org/2017/634.

[6] Kevin Burstinghaus-Steinbach, Christoph Krauß, Ruben Niederhagen, and MichaelSchneider. Post-quantum tls on embedded systems. Cryptology ePrint Archive, Re-port 2020/308, 2020. https://eprint.iacr.org/2020/308.

[7] Wikipedia Contributors. Asn.1. https://es.wikipedia.org/wiki/ASN.1. [Online;accessed 14-June-2020].

[8] Wikipedia Contributors. Transport layer security — wikipedia, the free encyclope-dia, 2020. https://en.wikipedia.org/wiki/Transport_Layer_Security. [Online;accessed 28-April-2020].

[9] W. Diffie and M. Hellman. New directions in cryptography. IEEE Transactions onInformation Theory, 22(6), 1976.

[10] Leo Ducas, Eike Kiltz, Tancrede Lepoint, Vadim Lyubashevsky, Peter Schwabe, Gre-gor Seiler, and Damien Stehle. Crystals-dilithium algorithm specifications and sup-porting documentation. 2017.

[11] Morris Dworkin. Sha-3 standard: Permutation-based hash and extendable-outputfunctions. 2015.

44

Page 46: Secure IoT for the future - esat.kuleuven.be · First of all, I would like to thank Professor Ingrid Verbauwhede for giving me the oppor-tunity of developing this project. Also my

[12] Jan-Pieter D’Anvers, Angshuman Karmakar, Sujoy Sinha Roy, and Frederik Ver-cauteren. Saber: Module-lwr based key exchange, cpa-secure encryption and cca-secure kem. Cryptology ePrint Archive, Report 2018/230, 2018. https://eprint.

iacr.org/2018/230.

[13] Amos Fiat and Adi Shamir. How to prove yourself: Practical solutions to identifica-tion and signature problems. In Andrew M. Odlyzko, editor, Advances in Cryptology— CRYPTO’ 86, pages 186–194, Berlin, Heidelberg, 1987. Springer Berlin Heidelberg.

[14] Lov K. Grover. A fast quantum mechanical algorithm for database search, 1996.

[15] Jeffrey Hoffstein, Nick Howgrave-Graham, Jill Pipher, Joseph Silverman, and WilliamWhyte. Ntrusign: Digital signatures using the ntru lattice [superseded]. 11 2003.

[16] Stehle D. Langlois, A. Worst-case to average-case reductions for module lattices. des.codes cryptogr. 2015. https://doi.org/10.1145/1060590.1060603.

[17] ARM Limited. Mbed tls. https://github.com/ARMmbed/mbedtls.

[18] Vadim Lyubashevsky, Chris Peikert, and Oded Regev. On ideal lattices and learn-ing with errors over rings. In Henri Gilbert, editor, Advances in Cryptology –EUROCRYPT 2010, pages 1–23, Berlin, Heidelberg, 2010. Springer Berlin Heidel-berg.

[19] matthew arcus. Using the cycle counter registers on the rasp-berry pi 3, 2018. https://matthewarcus.wordpress.com/2018/01/27/

using-the-cycle-counter-registers-on-the-raspberry-pi-3/.

[20] David Mcgrew and John Viega. The galois/counter mode of operation (gcm), 022004.

[21] Phong Q. Nguyen and Oded Regev. Learning a parallelepiped: Cryptanalysis ofggh and ntru signatures. In Serge Vaudenay, editor, Advances in Cryptology -EUROCRYPT 2006, pages 271–288, Berlin, Heidelberg, 2006. Springer Berlin Hei-delberg.

[22] National Institute of Standards and Technology. Sha-2 standard: Secure hash stan-dard. S Publication 180-2, 2002.

[23] National Institute of Standards and Technology. Announcing request for nominationsfor public-key post-quantum cryptographic algorithms, 2016.

[24] John Proos and Christof Zalka. Shor’s discrete logarithm quantum algorithm forelliptic curves. QIC 3 (No. 4) (2003) pp.317-344, 2004.

[25] Oded Regev. On lattices, learning with errors, random linear codes, and cryptog-raphy. In Proceedings of the Thirty-Seventh Annual ACM Symposium on Theoryof Computing, STOC ’05, page 84–93, New York, NY, USA, 2005. Association forComputing Machinery.

[26] R. L. Rivest, A. Shamir, and L. Adleman. A method for obtaining digital signaturesand public-key cryptosystems. Commun. ACM, 21(2):120–126, February 1978.

[27] Peter W. Shor. Polynomial time algorithms for prime factorization and discretelogarithms on a quantum computer. SIAM J.Sci.Statist.Comput. 26 (1997) 1484,1996.

45