HSM SECURITY Securing PKCS#11 Interfaces

Whitepaper v1.9 August 2019 Cryptosense | HSM Security Whitepaper 2

Contents

1. Introduction 3 2. Brief History of PKCS#11 3 3. Overview of PKCS#11 Design 3 4. Threat Scenario and Security Properties for PKCS#11 4 5. Attacking PKCS#11 HSM Security 5 5.1. Memory corruption attacks 5 5.2. Non-compliant PKCS#11 Implementations 6 5.3. Errors in Crypto Implementation 7 5.4. Attacks on Compliant PKCS#11 Implementations 7 6. Errors in Using the HSM 9 6.1. Insecure Crypto Mechanisms 10 6.2. Misuse of Crypto 10 6.3. Management Failures 10 7. Summary 10 8. About Cryptosense 11 9. Bibliography 11

This document is protected by copyright. No part of the document may be reproduced or redistributed in any form by any means without the prior written authorization of Cryptosense. This document is provided “as is" without any warranty of any kind. Cryptosense SA cannot be held responsible for any misconduct or malicious use of this document by a third party or damage caused by any information this document contains. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

Cryptosense SA, 231 Rue Saint-Honoré, 75001 Paris France

cryptosense.com © Cryptosense 2019 Cryptosense | HSM Security Whitepaper 3

1. Introduction Modern applications that use usually access that functionality via an application program interface (API) to a software or hardware cryptographic provider. Security-critical applications often make use of Hardware Security Modules (HSMs): special purpose computers that provide high-speed cryptographic services whilst keeping key material inside a tamper- sensitive enclosure. Together with smart cards or similar chip-based tokens, they form the backbone of many modern cryptographic applications in diverse sectors from banking to automotive.

HSMs and smart cards typically undergo a security certification procedure such as FIPS 140 or Common Criteria that examines tamper resistance and susceptibility to side channel attacks amongst other things. However, neither examines the security of the interface of the device. In fact, it would be hard to categorically state that the interface is secure, since each user will typically choose different configuration options that may affect security, and use of the interface by applications must also be taken into account.

The most commonly used API standard is RSA PKCS#11 [3], also known as Cryptoki. Following convention we will refer to PKCS#11 to mean the API itself rather than the document that defines it. While PKCS#11 has important benefits for interoperability since it is so widely supported, it is a large and open standard supporting a wide range of use cases. This makes it extremely tricky to implement correctly, and difficult to configure and use in a secure way.

In this white paper, we discuss attacks on systems using the PKCS#11 API. We consider what it means for an interface to be secure, and we discuss how to audit applications’ use of the API. There will be plenty of concrete examples of attacks on real devices, and we will explain how to detect these issues using Cryptosense Analyzer Platform.

2. Brief History of PKCS#11 The Public Key Cryptography Standards (PKCS) were proposed by RSA Inc, the company set up to commercialise the patent on the RSA and signature algorithms. The first standard in the series, PKCS#1, describes the required mathematical properties of RSA keys, how to perform RSA encryption, decryption, signing, and verification using a standard format etc. Further standards described password-based cryptography, various aspects of Public Key Infrastructure, Diffie-Hellman Key Agreement.

Many of the PKCS have been abandoned or fallen out of use, but PKCS#11, the standard that defines the Cryptoki interface for cryptographic hardware, was handed over to the OASIS PKCS#11 Technical Committee in 2012, who continue to revise and develop it. The first version (v1.0) of PKCS#11 was published in 1995. The current version is 2.40, released in 2015. Version 3.0 is in preparation.

3. Overview of PKCS#11 Design RSA PKCS#11 describes its API in just under 400 pages [3]. Here we give just a brief description to enable understanding of the various families of vulnerabilities. © Cryptosense 2019 Cryptosense | HSM Security Whitepaper 4

The API is stateful, maintaining in particular session state, operation state for e.g. encryption of large chunks of data, and information about cryptographic objects. In a PKCS#11-based API, applications initiate a session with the cryptographic token, by supplying a PIN. Once a session is initiated, the application may access the objects stored on the token, such as keys and certificates.

Objects are referenced in the API via handles, which can be thought of as pointers to or names for the objects. Objects have attributes, which may be e.g. the value of a key, or metadata giving properties of the object, e.g. whether the key may be used for encryption, or for encrypting other keys. New objects can be created by calling a key generation command, or by ‘unwrapping’ an encrypted key packet. In both cases a fresh handle is returned.

When a function in the token’s API is called with a reference to a particular object, the token first checks that the attributes of the object allow it to be used for that function. For example, if the encrypt function is called with the handle for a particular key, that key must have the CKA_ ENCRYPT encrypt attribute set to true. To protect a key from being revealed, the attribute CKA_SENSITIVE can be set to true. This means that requests to view the object’s key value via the API will result in an error message. Further protection can be given to a key by setting the CKA_EXTRACTABLE attribute to false. In this case, even a request to wrap the key, i.e. export it from the device encrypted, will be refused.

4. Threat Scenario and Security Properties for PKCS#11 The API between applications and cryptographic services is a natural trust boundary. We would expect a well-designed interface to maintain some security properties even if the application becomes compromised. This is indeed what PKCS#11 aims to do, as stated (in a rather roundabout way) in the Security Considerations section of the standard [9]:

As an interface to cryptographic devices, Cryptoki provides a basis for security in a computer or communications system. Two of the particular features of the interface that facilitate such security are the following:

1. “Access to private objects on the token, and possibly to cryptographic functions and/or certificates on the token as well, requires a PIN. Thus, possessing the cryptographic device that implements the token may not be sufficient to use it; the PIN may also be needed. 2. Additional protection can be given to private keys and secret keys by marking them as “sensitive” or “unextractable”. Sensitive keys cannot be revealed in plaintext off the token, and unextractable keys cannot be revealed off the token even when encrypted (though they can still be used as keys).” In PKCS#11, the PIN required to open a session on the cryptographic device is passed directly from the application to the device, hence if the application is compromised, the PIN will typically be compromised as well, as the standard notes:

“While the token itself may be secure, one must also consider the security of the operating system by which the application interfaces to it, especially since the PIN may be passed through the operating system. This can make it easy for a rogue application on the operating system to obtain the PIN; it is also possible that other devices monitoring communication lines to the © Cryptosense 2019 Cryptosense | HSM Security Whitepaper 5

cryptographic device can obtain the PIN. Rogue applications and devices may also change the commands sent to the cryptographic device to obtain services other than what the application requested.

[..]

“We note that none of the attacks just described can compromise keys marked “sensitive”, since a key that is sensitive will always remain sensitive. Similarly, a key that is unextractable cannot be modified to be extractable.”

Real-world instances of attacks where the intruder has obtained direct access to the HSM API include the RBS Worldpay compromise [1] and DigiNotar breach [2].

To summarise, the aim of the PKCS#11 API is to protect SENSITIVE and UNEXTRACTABLE keys on the device no matter whether the PIN has been intercepted and the application compromised so that it can send any sequence of PKCS#11 calls to the interface. In the rest of this whitepaper, we will concentrate on attacks on precisely these properties.

5. Attacking PKCS#11 HSM Security We have established a threat scenario where an attacker has full access to the PKCS#11 API using legitimate user credentials, and an objective to obtain the values of the “sensitive” and “unextractable” keys inside. Below we discuss the various ways this can be achieved.

5.1. Memory corruption attacks The first thing to note is that PKCS#11 describes a large low-level C API, with buffers, pointers, Type-Length-Value lists, etc., all of which must be carefully managed to avoid buffer overruns or other memory corruption based attacks. Like any large and complex system of this nature, bugs are quite common in practice. Sometimes, partial input sanitisation takes place in the PKCS#11 driver on the client machine rather than in the HSM itself, meaning that an attacker can bypass the checks to force invalid calls into the HSM and trigger a memory management error. Exploiting such errors to extract keys requires some effort, but catastrophic examples have been seen in the wild (see inset box). Even if key material is not extracted, an attack that requires a manual reboot of an HSM in a data center can have serious consequences for applications where availability is critical.

Testing for such issues is tricky for HSM implementers, and even more so for users who do not have access to source code. A good approach is to use fuzzing, a technique which involves systematically constructing a stream of deliberately invalid inputs and sending them to the interface to try to trigger issues. The Cryptosense PKCS#11 Fuzzer employs a mutation-based approach, which means taking a valid command input and changing it slightly to trigger a corner case. It employs advanced detection of memory corruption errors by spotting inconsistencies in command responses, and the ability to report on exact commands that trigger segmentation faults even when the PKCS#11 driver crashes. Cryptosense PKCS#11 Fuzzer has been used to discover dozens of memory management errors in HSMs (e.g. [10]) and is now used by certain HSM users as part of their permanent security assurance procedure for all new HSM firmware. © Cryptosense 2019 Cryptosense | HSM Security Whitepaper 6

Memory Management attacks - Ledger attack on Safenet Protect Server PSI-E2/ PSE2.

In June 2019, Ledger researchers Gabriel Campana and Jean-Baptiste Bédrune announced attacks on the Safenet Protect Server HSM. They used legitimate SDK access to their test HSM to upload a firmware module that would give them a shell inside the HSM. They then used the shell to run a fuzzer on the internal implementation of PKCS#11 commands to find reliable, exploitable buffer overflows. They checked they could exploit these buffer overflows from outside the HSM, i.e. by just calling the PKCS#11 driver from the host machine. Finally they wrote a payload that would override access control for firmware update and dump all the HSM secrets, and uploaded it to the HSM.

Gemalto-Safenet had already patched the firmware before the attacks were made public, but it’s important to note that the firmware update backdoor is persistent – a subsequent update will not fix it [8].

5.2. Non-compliant PKCS#11 Implementations The PKCS#11 Standard contains a number of important footnotes and implementation details that are critical for the security of key-storage. However, perhaps as a result of the size of the standard and the absence of API compliance testing from the FIPS or Common Criteria validation process, some implementations omit certain details, which results in simple single-command attacks on the API.

For example, in Section 7 of the standard [3] it is specified thatGetAttribute should not return the value of a key it is has either the attribute CKA_SENSITIVE set to TRUE or the attribute CKA_EXTRACTABLE set to FALSE. Unfortunately, real implementations sometimes miss one or other of these protections, leaving an open door for attackers. Another typical mistake is to allow these protection attributes to be turned off, something that the standard forbids, but several implementations allow (see inset).

Attacks on Key Protection

In an article published at ACM CCS in 2010 [6], Centenaro et al tested a number of PKCS#11 security tokens to see whether their implementations handled the CKA_SENSITIVE and CKA_EXTRACTABLE attributes in a compliant way. Several were found to include errors that allowed sensitive or unextractable keys to be obtained by sending a single C_ GetAttribute command to the interface, including certain models made by Feijtian, Gemalto, Siemens and RSA (see CVE-2010-3321).

There are also more subtle compliance failures that can lead to security issues, such as not correctly preserving the CKA_SENSITIVE and CKA_EXTRACTABLE attributes when an object is copied using the C_CopyObject command, or not calculating them correctly when new objects are created using the C_DeriveKey operation. © Cryptosense 2019 Cryptosense | HSM Security Whitepaper 7

To determine if an HSM implementation exhibits such issues, Cryptosense Analyzer for PKCS#11 runs the trace of calls and responses obtained from the Cryptosense Fuzzer through more than 100 compliance criteria tests, including all the above issues as well as others associated with secure defaults and correct rejection of invaid inputs.

5.3. Errors in Crypto Implementation In addition to key-storage, the security of a cryptographic API relies on the secure implementation of the cryptographic algorithms it provides. The FIPS or Common Criteria validation process typically includes checking that the algorithms correctly respond to the NIST test vectors, but it does not include checking for errors in padding validation, parsing, or other similar issues that can compromise cryptographic security (see inset box). Cryptosense Analyzer for PKCS#11 includes test rules for these issues.

Attacks on Crypto Implementation Bugs

In 2012, Bardou et al published a paper at the IACR CRYPTO conference that included the results of testing PKCS#11 implementations for padding oracle attacks on RSA PKCS#1v1.5 and AES-CBC Encryption. These kinds of attacks are particularly serious in the context of PKCS#11 since if they can be used on the C_Unwrap command, they can be leveraged to obtain the value of a sensitive key. The results showed that several implementations, including models by Safenet, RSA and Siemens, contained errors in their padding validation code that made the attacks much more potent and hence more practical. The PKCS#11 standard now contains a specific note in the security section about padding oracle issues, but other bugs in crypto implementations continue to emerge (see e.g. [8]).

5.4. Attacks on Compliant PKCS#11 Implementations Unfortunately, compliance to the PKCS#11 standard does not imply security. This was first highlighted in a paper by Jolyon Clulow at the CHES conference in 2003 [5], where he gave a number of attacks on fully compliant PKCS#11 implementations. Examples of these attacks continue to be found on real devices (see inset) while further variations of the attacks have also been discovered.

Here we give a sample of the kinds of vulnerabilities that can be found in compliant implementations, in particular when combinations of several commands are considered. Further examples can be found in the literature [4,5,6].

Cryptosense Analyzer for PKCS#11 automates detection of these attacks by applying a set of vulnerability detection rules that model the availability of command combinations for all of the attacks below. Many HSMs include features that allow the configuration of the PKCS#11 interface to be changed. For example, some commands can be disabled or their use restricted to certain patterns of parameters. While these options are welcome and indeed necessary for avoiding some of the attacks below, it is not always clear what the consequences are of each combination of options. Indeed, the range of different options can be baffling. Cryptosense Analyzer helps to © Cryptosense 2019 Cryptosense | HSM Security Whitepaper 8

find secure configurations in two ways. First, it presents all the attacks found in a simple report. Secondly, after changes have been made, one can simply re-run the testing phase to assess the security of the new configuration 5.4.1. Conflicting Key Roles

It is often possible to give keys more than one role via their CK_ATTRIBUTE settings, in a way that leads to insecure key management. For a simple example, suppose a key k1 stored on the device with the CKA_WRAP attribute set to TRUE, allowing it to be used by the C_WrapKey command to encrypt another key. Suppose it also has the CKA_DECRYPT attribute set. In that case a simple attack is possible on any sensitive, extractable key: the attacker simply calls wrap and then decrypt as shown below (we write {x}y to denote x encrypted by key y, and &k to denote a handle pointing to a key k. We give only the pertinent parameters in the PKCS#11 command calls).

Target of the attack: A symmetric key k, present on the device with handle &k, and with attributes CKA_SENSITIVE, CKA_EXTRACTABLE set.

1. C_GenerateKey({CKA_WRAP,CKA_DECRYPT}) (generates a new key k1 with WRAP, DECRYPT set) 2. C_WrapKey(&k1 ,&k) (gives {k}k1) 3. C_Decrypt({k}k1, &k1) (gives k as plaintext) Note that even if key generation commands prevent conflicts, the second role could be given to a copy of the key or could be applied by changing attributes. There are also similar attacks exploiting C_Encrypt/C_UnwrapKey conflicts [5][6]. 5.4.2. Insecure Key Export

It can be possible to encrypt a sensitive key with a weaker key by calling the C_WrapKey command. Here’s a simple example using the C_CreateKey command. Target of the attack: Symmetric key k, present on the device with handle &k, and with attributes CKA_SENSITIVE, CKA_EXTRACTABLE set.

1. C_CreateKey(k1 ,{CKA WRAP}) (generates a new handle for known cleartext key k1 with WRAP set) 2. C_WrapKey(&k1 ,&k) (gives {k}k1) 3. Offline Decrypt {k}k1 using k1 (gives k as plaintext)

In other variations, the weaker wrapping key might be non-sensitive (i.e. with the attribute CKA_ SENSITIVE set to FALSE, and hence readable), or sensitive but already known by the attacker (a so-called Trojan key), or it may be a shorter key than the wrapped key. © Cryptosense 2019 Cryptosense | HSM Security Whitepaper 9

5.4.3. Insecure Key Import It can be possible to obtain the value of an encrypted key presented for import at the PKCS#11 interface by manipulating the C_UnwrapKey command. Well-known examples include the padding oracle attacks on RSA PKCS#1v1.5 and CBC_PAD mentioned above [4].

Other examples include using C_UnwrapKey to create a non-sensitive copy of a sensitive key, and private key modification attacks 5[ , 6]. 5.4.4. Insecure Attribute Change

PKCS#11 gives guidance about which CK_ATTRIBUTES can be modified and in what sense (i.e. from FALSE to TRUE or from TRUE to FALSE). Unfortunately this guidance is not always followed, and as mentioned in section 2.2, it can be possible to downgrade the security of a key using C_SetAttributes. Even if the guidance is followed, an attacker can sometimes upgrade key permissions e.g. to create a conflict by exporting and importing keys. 5.4.5. Insecure Key Derivation It is possible to abuse the facilities provided by PKCS#11 for key derivation to obtain either the master key or the derived key. For a simple example, suppose we are using C_DeriveKey to obtain sensitive keys from a master key by encryption. If the master key also has the attribute CKA_ENCRYPT set, the derived keys can easily be obtained using C_Encrypt. There are also attacks based on constructing a reduced key space using extracted bits, and parallel key search attacks [5].

Attacking Key Derivation

While many of the attacks in Clulow’s 2003 paper [5] concern only sensitive, extractable keys, several also apply to unextractable keys. This includes a family of attacks on the C_DeriveKey operation, designed to generate a new key from existing key material. Using the mechanism CKM_EXTRACT_KEY_FROM_KEY, which simply selects bits from an existing key, Clulow showed how to generate a deliberately short key which can then be attacked by brute force, and repeat this process to obtain all the bits of a longer key. In 2015, researchers discovered how to attack the Safenet Luna G5 using a variation of this method [11], resulting in CVE-2015-5464.

6. Errors in Using the HSM Another source of vulnerabilities in a PKCS#11 stack is the application itself. Even if the device interface has been implemented and set up correctly to avoid all the vulnerabilities mentioned above, it is still possible for things to go wrong. Below we give some examples.

To prevent these errors, application cryptography use and key management needs to be audited continually as the application is developed. Cryptosense PKCS#11 Tracer sits between the application and the HSM and logs all calls to the interface. The trace can be uploaded to © Cryptosense 2019 Cryptosense | HSM Security Whitepaper 10

the Cryptosense Analyzer Platform for full automated audit of cryptographic security and key management issues like those we explain below. It can be integrated into CI to detect errors early in the development lifecycle.

6.1. Insecure Crypto Mechanisms PKCS#11 contains a large number of “legacy” algorithms that, thanks to advances in computing power and , are now considered insecure, like MD5, and single DES. There are also mechanisms that use insecure padding methods like RSA PKCS#1v1.5 (CKM_RSA_PKCS) or “raw” unpadded encryption (CKM_RSA_X_509). Version 2.40 of PKCS#11 retired some of these mechanisms to a “historical” mechanism section, but they are frequently still available on HSMs due to the need to support legacy applications.

6.2. Misuse of Crypto Sometimes the problem comes from a misunderstanding between the application and the provider over the properties of a certain crypto mechanism. A classic example is the use of the mode CBC (cipher block chaining), available in PKCS#11 for all block ciphers (CKM_ AES_CBC, CKM_3DES_CBC, etc.). To encrypt, the application must supply an initialization vector. A common mistake, still seen widely, is to always supply 0. This results in identical plaintexts giving identical . Worse, plaintexts that are identical just in their first few blocks will have identical prefixes. In fact with CBC, in order to achieve chosen-plaintext security, the IV must be random (even a value just used once is not good enough). Finally, even when used with a random IV, CBC on its own only ensures confidentiality, not integrity. In practice this means that chosen- attacks are often possible, in particular padding oracle attacks against modes like CKM_AES_CBC_PAD are common in PKCS#11 implementations [4]. 6.3. Key Management Failures As we saw above, finding the right setup for PKCS#11 key management commands in terms of restrictions based on attribute settings is no easy business. However, even once a good configuration has been found, it is still possible for an application error to destroy security. An easy example is if the application fails to generate keys with the correct settings for the CKA_ SENSITIVE or CKA_EXTRACTABLE attributes. Sometimes this is because the application code has been tested in a development environment where the default values assigned to non-specified attributes were different from those in the production environment.

7. Summary We’ve seen that there are a large variety of security issues to take care of when using PKCS#11 cryptographic devices: memory-management bugs, non-compliances to the standards resulting in vulnerabilities, attacks that come from calling compliant commands in an unexpected way, and vulnerabilities caused by the use of the HSM by the application. These issues result in real attacks and even real exploits in the wild [1,2]. Cryptosense Analyzer is the only comprehensive toolsuite available for automated security audit of a PKCS#11 implementation. To find out more about its capabilities for PKCS#11 as well as other cryptographic APIs go to cryptosense.com/analyzer. © Cryptosense 2019 Cryptosense | HSM Security Whitepaper 11

8. About Cryptosense Based in Paris, France, Cryptosense SA creates software to help users of cryptography stay secure. A spin-off of the French institute for computer science research (INRIA) and a collaborator of the University of Venice Ca’ Foscari, Cryptosense’s founders combine more than 40 years experience in research and industry.

Cryptosense software is used to test the cryptographic systems that secure over half of daily interbank messages, over half of daily forex trades, and the world’s largest financial transaction database.

To request a quote for an audit of your PKCS#11 infrastructure, email [email protected]. or to obtain a copy of our other whitepapers on Java crypto security, cloud crypto services and more, go to https://cryptosense.com/whitepapers/

9. Bibliography [1] Grand Jury Indictment of Pleschuck et al, http://cryptosense.com/wp-content/uploads/2014/11/ rbs-supercediing-indictment-worldpay.pdf

[2] Black Tulip Report, http://cryptosense.com/wp-content/uploads/2014/11/black-tulip-update.pdf

[3] RSA PKCS#11 v2.20, http://cryptosense.com/wp-content/uploads/2014/11/pkcs-11v2-20.pdf

[4] R. Bardou, R. Focardi, Y. Kawamoto, L. Simionato, G. Steel and J.-K. Tsay. Efficient Padding Oracle Attacks on Cryptographic Hardware. In CRYPTO'12, LNCS 7417, pages 608-625. Springer, 2012.

[5] Clulow, J.S. "On the Security of PKCS#11", CHES 2003, LNCS 2779, 2003

[6] M. Bortolozzo, M. Centenaro, R. Focardi and G. Steel. Attacking and Fixing PKCS#11 Security Tokens. In CCS'10, pages 260-269. ACM Press, 2010.

[7] OWASP Cryptographic Storage Cheat Sheet, July 2014, https://www.owasp.org/index.php/ Cryptographic_Storage_Cheat_Sheet#Rule_-_Ensure_that_the_cryptographic_protection_ remains_secure_even_if_access_controls_fail

[8] How Ledger Hacked an HSM https://cryptosense.com/blog/how-ledger-hacked-an-hsm/

[9] PKCS#11 Usage Guide. Security Considerations. http://docs.oasis-open.org/pkcs11/pkcs11-ug/ v2.40/cn02/pkcs11-ug-v2.40-cn02.html#_Toc406759998

[10] Cryptosense Software Finds Key-Disabling Bug in Thales HSM https://cryptosense.com/blog/ cryptosense-software-finds-key-disabling-bug-in-thales-hsm/

[11] On Safenet HSM key-extraction vulnerability CVE-2015-5464 https://randomoracle. wordpress.com/2015/08/13/safenet-hsm-key-extraction-vulnerability-part-i/ © Cryptosense 2019