Security

Security


Digital signatures and certificates

A digital signature is an electronic, encrypted, stamp of authentication on digital information such as email messages, macros, or electronic documents.
A digital signature algorithm includes a signature generation process and a signature verification process.
A signature confirms that the information originated from the signer and has not been altered.

Cryptographic Message Syntax (a.k.a PKCS #7) is a very commonly used format for signed data.

Digital signatures rely on public and private keys.
Public Key Infrastructure (PKI) enforces additional requirements, such as the Certificate Authority (CA), a type of Trust Service Provider, are third-party organizations that can provide the necessary digital certificates.
A digital certificate is an electronic document issued by a Certificate Authority (CA).
It contains the public key for a digital signature and specifies the identity associated with the key, such as the name of an organization.
When you send a digitally-signed macro or document, you also send your certificate and public key.
Certificates and keys are stored in the files in several formats:
  • .pem
  • A privacy-enhanced mail (.pem) format file begins and ends with the following lines:
    
    -----BEGIN CERTIFICATE-----
    -----END CERTIFICATE-----    
        
  • .pfx (PKCS12)
  • A PKCS12 file is a portable file that contains a certificate and a corresponding private key.

PKI的運作方式與原理

PKI(Public Key Infrastructure,公開金鑰基礎建設架構)是以公鑰密碼學為基礎衍生出來的架構,其基礎建置包含憑證機構(Certification Authority ,CA)、註冊中心(Register Authority, RA)、目錄服務(Directory Service ,DS)伺服器。
由RA統籌、審核用戶的憑證申請,將憑證申請送至CA處理後發出憑證,並將憑證公告至DS中。
在使用憑證的過程中,除了對憑證的信任關係與憑證本身的正確性做檢查外,並透過憑證廢止清冊(Certificate Revocation List ,CRL)對憑證的狀態做確認檢查,了解憑證是否因某種原因而遭廢棄。
憑證就像是個人的身分證,其內容包括憑證序號、用戶名稱、公開金鑰(Public Key)、憑證有效期限等。

CA必須同時為傳送者與接收者所信任,而由具公信力的第三者來擔任;由CA經過認證,簽發公開金鑰憑證,以作為檢驗私密金鑰的憑證。
PKI包含一支公開金鑰(Public Key)與一支私密金鑰(Private Key),前者公開給大眾知道,後者由持有者保管。
這一組金鑰為一組電子密碼,可作為檢驗身分之用,且具有相對應的關係,其中一支金鑰將訊息進行加密,另一支金鑰則可進行解密而得到原來的訊息。

私鑰儲存設備包含電腦之硬碟或軟碟、加解密運算卡、Smart Card(智慧卡)或Token(權杖)等相關儲存元件。
Smart Card具有硬體保護機制,安全性較高。

A君(傳送者)要傳送資料給B君(接收者)時,A君先到CA取得B君的公開金鑰以進行資料加密,再將資料傳送給B君,由B君用自己的私鑰進行解密;
B君到CA取得A君的公開金鑰,確認這一組公鑰/私鑰是否可以比對,若比對無誤,即可確定資料的傳送者的確是A君。
至於資料是否被竄改就要經過訊息摘要(Message Digest)的比對。

Basic structure of a X.509 certificate

For signature calculation, the data that is to be signed is encoded using the ASN.1 distinguished encoding rules (DER) [X.690].
ASN.1 DER encoding is a tag, length, value encoding system for each element.

The Certificate is a SEQUENCE of three required fields.
X.509 v3 certificate basic syntax:


   Certificate  ::=  SEQUENCE  {
        tbsCertificate       TBSCertificate,
        signatureAlgorithm   AlgorithmIdentifier,
        signatureValue       BIT STRING  }
Certificate is a SEQUENCE contains an ordered field of one or more types:
  • tbsCertificate
  • The field contains the names of the subject and issuer, a public key associated with the subject, a validity period, and other associated information. (tbs: to be signed)
    
    TBSCertificate  ::=  SEQUENCE  {
            version         [0]  EXPLICIT Version DEFAULT v1,
            serialNumber         CertificateSerialNumber,
            signature            AlgorithmIdentifier,
            issuer               Name,
            validity             Validity,
            subject              Name,
            subjectPublicKeyInfo SubjectPublicKeyInfo,
            issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
                                 -- If present, version MUST be v2 or v3
            subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
                                 -- If present, version MUST be v2 or v3
            extensions      [3]  EXPLICIT Extensions OPTIONAL
                                 -- If present, version MUST be v3
            }    
        
    • version
    • This field describes the version of the encoded certificate.
      
         Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }            
                  
    • serialNumber
    • The serial number MUST be a positive integer assigned by the CA to each certificate. It MUST be unique for each certificate issued by a given CA
      
          CertificateSerialNumber  ::=  INTEGER           
                  
    • signature
    • This field contains the algorithm identifier for the algorithm used by the CA to sign the certificate.
      
                  
                  
    • issuer
    • The issuer field identifies the entity that has signed and issued the certificate.
      
                  
                  
    • validity
    • The certificate validity period is the time interval during which the CA warrants that it will maintain information about the status of the certificate.
      
         Validity ::= SEQUENCE {
              notBefore      Time,
              notAfter       Time }
                  
      • Time
      • 
           Time ::= CHOICE {
                utcTime        UTCTime,
                generalTime    GeneralizedTime }                    
                            
      • UTCTime
      • The universal time type, UTCTime, is a standard ASN.1 type intended for representation of dates and time.
      • GeneralizedTime
      • GeneralizedTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST include seconds (i.e., times are YYYYMMDDHHMMSSZ)
    • subject
    • The subject field identifies the entity associated with the public key stored in the subject public key field.
    • subjectPublicKeyInfo
    • This field is used to carry the public key and identify the algorithm with which the key is used (e.g., RSA, DSA, or Diffie-Hellman).
      
         SubjectPublicKeyInfo  ::=  SEQUENCE  {
              algorithm            AlgorithmIdentifier,
              subjectPublicKey     BIT STRING  }            
                  
    • issuerUniqueID
    • only appear if the version is 2 or 3.
      
                  
                  
    • subjectUniqueID
    • only appear if the version is 2 or 3.
      
                  
                  
    • extensions
    • The extensions defined for X.509 v3 certificates provide methods for associating additional attributes with users or public keys and for managing relationships between CAs.
      
         Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension            
                  
  • signatureAlgorithm
  • Identifier for the cryptographic algorithm used by the CA to sign this certificate.
    
    AlgorithmIdentifier  ::=  SEQUENCE  {
            algorithm               OBJECT IDENTIFIER,
            parameters              ANY DEFINED BY algorithm OPTIONAL  }    
        
  • signatureValue
  • Digital signature computed upon the ASN.1 DER encoded tbsCertificate.
    The ASN.1 DER encoded tbsCertificate is used as the input to the signature function.
    This signature value is encoded as a BIT STRING and included in the signature field.
    By generating this signature, a CA certifies the validity of the information in the tbsCertificate field.
    
        
        
In order to verify that a certificate was signed by a specific CA, we would need to possess the following:
  • Public key of the CA (issuer)
  • Signature and Algorithm used to generate the signature

OpenSSL Quick Reference Guide

OpenSSL is an open-source command line tool that is commonly used to generate private keys, create CSRs, install your SSL/TLS certificate, and identify certificate information.

Checking Your OpenSSL Version


$ openssl version -a

OpenSSL and CSR Creation

The first step to obtaining an SSL certificate is using OpenSSL to create a certificate signing request (CSR) that can be sent to a Certificate Authority (CA).
The CSR contains the common name(s) you want your certificate to secure, information about your company, and your public key.
In order for a CSR to be created, it needs to have a private key from which the public key is extracted.

Deciding on Key Generation Options

When generating a key, you have to decide three things:
  • Key Algorithm
  • Key Size
  • The smallest key sizes allowed for SSL certificates is at least 2048 when using RSA and 256 when using ECDSA.
  • Passphrase
  • If used, the private key will be encrypted using the specified encryption method, and it will be impossible to use without the passphrase.

Generating Your Private Key

To generate your private key using the RSA algorithm:

$ openssl genrsa -out yourdomain.key 2048
Generating RSA private key, 2048 bit long modulus (2 primes)
......................+++++
......+++++
e is 65537 (0x010001)
This command generates a private key in your current directory named yourdomain.key (-out yourdomain.key).
The contents (PEM format) of the private key is encoded, the following command is usedto decode the private key and view its contents :

$ openssl rsa -test -in yourdomain.key -noout
The -noout switch omits the output of the encoded version of the private key.

Extracting Your Public Key

The private key file contains both the private key and the public key.
Use the following command to extract your public key from ypur private key file:

$ openssl rsa -in yourdomain.key -pubout -out yourdomain_public.key

Creating Your CSR(Certificate Signing Request)

After generating your private key, you are ready to create your CSR.
The CSR is created using the PEM format and contains the public key portion of the private key as well as information about you (or your company).
To create a CSR using your newly generated private key:

$ openssl req -new -key yourdomain.key -out yourdomain.csr
After entering the command, you will be asked series of questions.
Some of the above CSR questions have default values pulled from the OpenSSL configuration file located in the OPENSSLDIR.

You can provide all the necessary information and disable question prompts by providing the CSR information (-subj):


$ openssl req -new -key yourdomain.key -out yourdomain.csr \
-subj "/C=US/ST=Utah/L=Lehi/O=Your Company, Inc./OU=IT/CN=yourdomain.com"

Creating Your CSR with One Command

You can generate a private key and then create a CSR in one step,

$ openssl req -new \
-newkey rsa:2048 -nodes -keyout  yourdomain.key 
-out yourdomain.csr \
-subj "/C=US/ST=Utah/L=Lehi/O=Your Company, Inc./OU=IT/CN=yourdomain.com"

Verifying CSR Information

Use the following command to view the information in your CSR before submitting it to a CA:

$ openssl req -text -in yourdomain.csr -noout -verify

Sending the CSR to the CA

Viewing Certificate Information

Use the following command to view the contents of your certificate:

$ openssl x509 -text -in yourdomain.crt -noout

Verifying Your Keys Match

The hash of the public key extracted from each file should be the same:

$ openssl pkey -pubout -in .\private.key | openssl sha256
$ openssl req -pubkey -in .\request.csr -noout | openssl sha256
$ openssl x509 -pubkey -in .\certificate.crt -noout | openssl sha256

Converting Certificate Formats

By default, OpenSSL generates keys and CSRs using the PEM format.

X.509 is a standard that defines the structure of the certificate. It defines the data fields that should be included in the SSL certificate.
X.509 uses a formal language called Abstract Syntax Notation One (ASN.1) to express the certificate's data structure.

There are different file formats of X.509 certificates.
The certificate files have different extensions based on the format and encoding they use.

  • PEM Format
  • The certificate file types can be .pem, .crt, .cer, or .key.
    PEM files use ASCII encoding,
    • certificate is contained between the statements
    • 
      ---- BEGIN CERTIFICATE---- 
      ----END CERTIFICATE----         
              
    • private key is contained between the statements
    • 
      ---- BEGIN RSA PRIVATE KEY-----
      -----END RSA PRIVATE KEY-----        
              
    • CSR is contained between the statements
    • 
      -----BEGIN CERTIFICATE REQUEST-----
      -----END CERTIFICATE REQUEST-----         
              
  • PKCS#7 Format
  • The PKCS#7 certificate uses Base64 ASCII encoding with file extension .p7b or .p7c.
    The P7B certificates are contained between the statements:
    
    -----BEGIN PKCS7-----
    -----END PKCS7-----
    		
  • DER Format
  • The DER certificates are in binary form.
    DER stores key and certificate information in two separate files and typically uses the same file extensions (i.e., .key, .crt, and .csr).
  • PKCS#12 Format
  • The PKCS#12 certificates are in binary form, contained in .pfx or .p12 files.
    The PKCS#12 format is an archival file that stores both the certificate and the private key.
    This format is useful for migrating certificates and keys from one system to another as it contains all the necessary files.
File format conversions:
  • PEM to PKCS#12
  • 
    $ openssl pkcs12 -export -name "yourdomain-digicert-(expiration date)" \
    -out yourdomain.pfx -inkey yourdomain.key -in yourdomain.crt    
        
    This command combines your private key (-inkey yourdomain.key) and your certificate (-in yourdomain.crt) into a single .pfx file (-out yourdomain.pfx) with a friendly name (-name "yourdomain-digicert-(expiration date)"), where the expiration date is the date that the certificate expires.
  • PKCS#12 to PEM
  • Extract the private key from a PKCS#12 (.pfx) file and convert it into a PEM encoded private key:
    
    $ openssl pkcs12 -in yourdomain.pfx -nocerts -out yourdomain.key -nodes 
        
    Extract the certificate from a PKCS#12 (.pfx) file and convert it into a PEM encoded certificate
    
    $ openssl pkcs12 -in yourdomain.pfx -nokeys -clcerts -out yourdomain.crt
        
  • PEM to DER
  • Convert a PEM encoded certificate into a DER encoded certificate:
    
    $ openssl x509 -inform PEM -in yourdomain.crt -outform DER -out yourdomain.der    
        
    Convert a PEM encoded private key into a DER encoded private key
    
    $ openssl rsa -inform PEM -in yourdomain.key -outform DER -out yourdomain_key.der    
        
  • DER to PEM
  • Convert a DER encoded certificate into a PEM encoded certificate:
    
    $ openssl x509 -inform DER -in yourdomain.der -outform PEM -out yourdomain.crt    
        
    Convert a DER encoded private key into a PEM encoded private key:
    
    $ openssl rsa -inform DER -in yourdomain_key.der -outform PEM -out yourdomain.key    
        

How to use OpenSSL: Hashes, digital signatures, and more

Cryptographic hashes

Modern Linux has md5sum and sha256sum. for computing file's hash.
OpenSSL itself provides similar command-line utilities.

In the command-line examples that follow, two input files are used as bitstring sources:

  • hashIn1.txt
  • This file contains:
    
    abc
            
    Using the Linux sha256sum utility and openssl:
    
    $ sha256sum hashIn1.txt
    9e83e05bbf9b5db17ac0deec3b7ce6cba983f6dc50531c7a919f28d5fb3696c3 hashIn1.txt
    $ openssl dgst -sha256 hashIn1.txt
    SHA256(hashIn1.txt)= 9e83e05bbf9b5db17ac0deec3b7ce6cba983f6dc50531c7a919f28d5fb3696c3
    		
  • hashIn2.txt
  • 
    1a2b3c
            
    Using the Linux sha256sum utility and openssl:
    
    $ sha256sum hashIn2.txt
    3eaac518777682bf4e8840dd012c0b104c2e16009083877675f00e995906ed13 hashIn2.txt
    $ openssl dgst -sha256 hashIn2.txt
    SHA256(hashIn2.txt)= 3eaac518777682bf4e8840dd012c0b104c2e16009083877675f00e995906ed13
    		

Digital signatures

When using OpenSSL to create private/pulic keys, there are two separate commands: one to create a private key, and another to extract the matching public key from the private one.
These key pairs are encoded in base64, and their sizes can be specified during this process.

The private key consists of numeric values, two of which (a modulus and an exponent) make up the public key.
Although the private key file contains the public key, the extracted public key does not reveal the value of the corresponding private key.
The pair’s private key is used to process a hash value for the target artifact (e.g., an email), thereby creating the signature.
On the other end, the receiver’s system uses the pair’s public key to verify the signature attached to the artifact.
To generate a 2048-bit RSA key pair with OpenSSL:


$ openssl genpkey -out privkey.pem -algorithm rsa 2048
We can drop the -algorithm rsa flag in this example because genpkey defaults to the type RSA.
Here’s a slice of the resulting privkey.pem file, which is in base64:

-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANnlAh4jSKgcNj/Z
JF4J4WdhkljP2R+TXVGuKVRtPkGAiLWE4BDbgsyKVLfs2EdjKL1U+/qtfhYsqhkK
…
-----END PRIVATE KEY-----
To extracts the pair’s public key from the private one:

$ openssl rsa -in privkey.pem -outform PEM -pubout -out pubkey.pem
If the file client is to be signed to generate a digest with SHA256:

$ openssl dgst -sha256 -sign privkey.pem -out sign.sha256 client
the resulting base64-encoded signature looks like:

h+e+3UPx++KKSlWKIk34fQ1g91XKHOGFRmjc0ZHPEyyjP6/lJ05SfjpAJxAPm075
VNfFwysvqRGmL0jkp/TTdwnDTwt756Ej4X3OwAVeYM7i5DCcjVsQf5+h7JycHKlM
o/Jd3kUIWUkZ8+Lk0ZwzNzhKJu6LM5KWtL+MhJ2DpVc=
Now, to verify the digital signature :
  1. decodes the base64 signature
  2. 
    $ openssl enc -base64 -d -in sign.sha256.base64 -out sign.sha256    
        
  3. verifies the signature
  4. 
    $ openssl dgst -sha256 -verify pubkey.pem -signature sign.sha256 client    
        

Digital certificates

Using digital signatures for data integrity checking in Linux

Digital signature implementation includes the following steps:
  • prepare the target binary file to be signed
  • The creation of two keys: private and public (certificate).
  • Binary file signing (ELF)
    • MD5/sha256 of the binary file is encrypted with the help of the private key;
    • The encrypted MD5/sha256 is written to a new .sig section of the binary file;
    • The certificate is saved to the ~/.ssh folder.


   #!/bin/bash
   
   KEY_DIR="$HOME/.ssh"
   PRIVATE_KEY="$KEY_DIR/priv.key"
   CERTIFICATE="$KEY_DIR/pub.crt"
   SUBJECT="/C=RU/ST=Nizhni Novgorod/L=Nizhniy Novgorod/O=Auriga/OU=DEV/CN=www.auriga.com"
   
   if [ "$#" = "0" ]; then
       echo "Usage: sign_elfs.sh   ... "
       exit 1;
   fi
   
   if [ ! -d "$KEY_DIR" ]; then
       # Control will enter here if $DIRECTORY does not exist.
       mkdir "$KEY_DIR"
   fi
   
   # Create private key and certificate
   openssl req -nodes -x509 -sha256 -newkey rsa:4096 -keyout "$PRIVATE_KEY" -out "$CERTIFICATE" -days 365 -subj "$SUBJECT"
   
   for ELF_BIN in $@; do
       ELF_BASE_NAME="${ELF_BIN##*/}"
       #       ELF_BIN_OLD="$ELF_BIN.old"
       ELF_BIN_SIGNATURE="$ELF_BASE_NAME.sha256"
       ELF_BIN_MD5="$ELF_BASE_NAME.md5"
   
       if [ ! -f "$ELF_BIN" ] || [ "x$ELF_BIN" = "x" ];then
           echo "Error: no such file $ELF_BIN"
       exit 1
       fi
   
       # Remove .sig section
       objcopy --remove-section=.sig "$ELF_BIN"
   
       # Add 512-byte section filled with zeros
       rm -f dummy.txt
       touch dummy.txt
       truncate --size=512 dummy.txt
       objcopy --add-section .sig=dummy.txt --set-section-flags .sig=noload,readonly "$ELF_BIN"
   
       # Create MD5 hash
       md5sum "$ELF_BIN" | awk '{ print $1 }' > "$KEY_DIR/$ELF_BIN_MD5"
   
       # Sign(Encrypt) MD5 hash file using private key
       openssl dgst -sha256 -sign "$PRIVATE_KEY" -out "$KEY_DIR/$ELF_BIN_SIGNATURE" "$KEY_DIR/$ELF_BIN_MD5"
   
       # Validate the signature(encrypted MD5 hash) using certificate
       openssl dgst -sha256 -verify <(openssl x509 -in "$CERTIFICATE" -pubkey -noout) -signature "$KEY_DIR/$ELF_BIN_SIGNATURE" "$KEY_DIR/$ELF_BIN_MD5"
   
       # Add the signature(encrypted MD5 hash) into ELF binary into .sig section
       echo "Add .sig section"
       objcopy --update-section .sig="$KEY_DIR/$ELF_BIN_SIGNATURE" --set-section-flags .sig=noload,readonly "$ELF_BIN" "$ELF_BIN"
   
       # Print .sig section
       echo "Check .sig section"
       objdump -sj .sig "$ELF_BIN"
   done
   
   rm -f dummy.txt
   
   ls -ls ~/.ssh

How to sign and verify using OpenSSL

4096-bit RSA key can be generated with OpenSSL :

$ openssl genrsa -out key.pem 4096
$ openssl rsa -in key.pem -pubout > key.pub
To sign a data file (data.zip in the example) then verify it:

$ openssl dgst -sign   key.pem -keyform PEM -sha256 -out       data.zip.sign -binary data.zip
$ openssl dgst -verify key.pub -keyform PEM -sha256 -signature data.zip.sign -binary data.zip
Verified OK

OTP

OTP stands for One-Time Programmable.
OTP is a hardware component inside the SoC.
The total size of OTP is several KB in general.

OTP can only be programmed once. If it is programmed incorrectly, the chip will become unusable.
The OTP’s layout is divided into two areas:

  • SOC-defined area
  • For ex.,
    Bit Address(decimal)length(bits)OTP Function
    0 - 191192Reserved by chip vendor
    192 - 22323OTP Lock (by customer)
    224 - 1587115647Reserved by chip vendor
    15872 - 1599128Unique ID used by chip vendor
  • customer-defined area
  • Bit Address(decimal)length(bits)OTP Function
    16128 - 162128Customer unique ID (hardware serial number)
    16256 - 16383128User defined
    16384 - 16511128HUK (mandatory for OPTEE)
    16512 - 16639128NONCE (Same slot of HUK)
    16640 - 16895256Monotonic Counter(prevent a “downgrade attack”)
    16896 - 17919256 x 4AES keys (for customized application use)
    17920 - 18943256 x 4ECC keys (for customized application use)
    18944 - 20479256 x 6User defined DX
    20480 - 2457540962048-bit pre-calculated data + 2048-bit RSA key (mandatory for secure boot ROT)

MD5 Message-Digest Algorithm


一種被廣泛使用的密碼雜湊函式,輸入不定長度資訊可以產生出一個固定長度128-bits(16位元組)的雜湊值(hash value).
將資料(如一段文字)運算變為另一固定長度值,是雜湊演算法的基礎原理。
1996年後被證實存在弱點,可以被加以破解,對於需要高度安全性的資料,專家一般建議改用其他演算法,如SHA-1。因此無法適用於安全性認證,如SSL公開金鑰認證或是數位簽章等用途。

以下是一個43位長的僅ASCII字母列的MD5雜湊:

MD5("The quick brown fox jumps over the lazy dog")
= 9e107d9d372bb6826bd81d3542a419d6

即使在原文中作一個小變化(比如用c取代d)其雜湊也會發生巨大的變化:

MD5("The quick brown fox jumps over the lazy cog")
= 1055d3e698d289f2af8663725127bd4b

空文的雜湊為:

MD5("")
= d41d8cd98f00b204e9800998ecf8427e

Python


import hashlib

data = "The quick brown fox jumps over the lazy dog"m = hashlib.md5()
m.update(data.encode("utf8"))
m.digest()
b'\x9e\x10}\x9d7+\xb6\x82k\xd8\x1d5B\xa4\x19\xd6'

Secure Device Provisioning

The device can be :
  • deployed with public keys and encryption keys (in OTP)
  • The secure boot chooses 2048-bit RSA and SHA2-256 crypto algorithm, the digital signature format is PKCS #1 v1.5.
  • disable the USB boot and JTAG by effuse setting.
  • USB boot mode is not available when secure boot is enabled.
    After the JTAG eFuse bit is set, JTAG is controlled by JTAG_EN register.
    If JTAG_EN register is not written, JTAG is disabled by default when secure boot is enabled.
  • chips have a Unique ID

Note

Introduction

  • Encryption/Decryption
    • DES
    • 3DES
    • RC4
    • TEA
    • XTEA
    • Blowfish
    • Twofish
    • CAST5
    • Salsa20
    • AES
  • Hashes
    • MD4
    • MD5
    • RIPEMD160
    • SHA1
    • SHA2
    • SHA3
  • Signature
    • RSA
      • PKCS1v15
      • PSS
    • ECDSA
    • P256
    • P384
    • P521
    • ED25519
  • Key exchange protocol
    • Diffie–Hellman key exchange
    • A method of securely exchanging cryptographic keys over a public channel.
      DH is one of the earliest practical examples of public key exchange.
      Each party generates a public/private key pair and distributes the public key.
      After obtaining an authentic copy of each other's public keys, a shared secret can be computed privately.
      The shared secret can be used, for instance, as the key for a symmetric cipher.
    • Elliptic-curve Diffie–Hellman (ECDH)
    • A key agreement protocol that allows two parties, each having an elliptic-curve public–private key pair, to establish a shared secret over an insecure channel.
      This shared secret may be directly used as a key, or to derive another key.
      The key, or the derived key, can then be used to encrypt subsequent communications using a symmetric-key cipher.
      It is a variant of the Diffie–Hellman protocol using elliptic-curve cryptography.
      The key wrap constructions are typically built from standard primitives such as block ciphers and cryptographic hash functions.
  • Key Wrap
  • Key wrap is an algorithms designed to encapsulate (encrypt) cryptographic key material.

Applied PKCS #11

Introduction

Portable computing devices such as smart cards, PCMCIA cards, and smart diskettes are ideal tools for implementing public-key cryptography, as they provide a way to store the private-key component of a public-key/private-key pair securely, under the control of a single user.
With such a device, a cryptographic application can utilize the device to perform the operations, with sensitive information such as private keys never being revealed.
As more applications are developed for public-key cryptography, a standard programming interface for these devices becomes increasingly valuable. This standard addresses this need.

PKCS#11 is the name given to a standard defining an API for cryptographic hardware.

The primary goal of Cryptoki was a lower-level programming interface that abstracts the details of the devices, and presents to the application a common model of the cryptographic device, called a "cryptographic token" (or simply "token").

Cryptoki's general model is illustrated in the following figure:

Cryptoki provides an interface to one or more cryptographic devices that are active in the system through a number of "slots".
Each slot, which corresponds to a physical reader or other device interface, may contain a token.
A token is typically "present in the slot" when a cryptographic device is present in the reader.
The point is that a system has some number of slots, and applications can connect to tokens in any or all of those slots.

Cryptoki hides these details of the underlying "device".
Cryptoki is likely to be implemented as a library supporting the functions in the interface, and applications will be linked to the library.
The kinds of devices and capabilities supported will depend on the particular Cryptoki library.

Cryptoki's logical view of a token is: a device that stores objects and can perform cryptographic functions.
"Token objects" are visible to all applications connected to the token that have sufficient permission, and remain on the token even after the "sessions" (connections between an application and the token) are closed and the token is removed from its slot.
"Session objects" are more temporary: whenever a session is closed by any means, all session objects created by that session are automatically destroyed. In addition, session objects are only visible to the application which created them.

A token can create and destroy objects, manipulate them, and search for them. It can also perform cryptographic functions with objects. A token may have an internal random number generator.

"Attributes" are characteristics that distinguish an instance of an object. In Cryptoki, there are general attributes, such as whether the object is private or public. There are also attributes that are specific to a particular type of object, such as a modulus or exponent for RSA keys.

This version of Cryptoki recognizes two token user types:

  • a Security Officer (SO)
  • the normal user
The role of the SO is to initialize a token and to set the normal user's PIN (or otherwise define, by some method outside the scope of this version of Cryptoki, how the normal user may be authenticated), and possibly to manipulate some public objects.
The normal user cannot log in until the SO has set the normal user's PIN.

To Cryptoki, an application becomes a "Cryptoki application" by calling the Cryptoki function C_Initialize from one of its threads; after this call is made, the application can call other Cryptoki functions.
When the application is done using Cryptoki, it calls the Cryptoki function C_Finalize and ceases to be a Cryptoki application.

Cryptoki requires that an application open one or more sessions with a token to gain access to the token's objects and functions.
A session provides a logical connection between the application and the token.
A session can be a read/write (R/W) session or a read-only (R/O) session. Read/write and read-only refer to the access to token objects, not to session objects.
In both session types, an application can create, read, write and destroy session objects, and read token objects. However, only in a read/write session can an application create, modify, and destroy token objects.

Concepts in PKCS #11

Slots and Tokens

A slot originally referred to a single card slot on a smartcard device that could accept a token.
A token was a smartcard containing a secret.
You would insert your smartcard (token) into the slot, and use its secret to do cryptographic operations.

Tokens are secured with a passphrase (PIN).

Mechanisms and Capabilities

In PKCS #11 mechanisms refer to the combination of cipher (e.g. AES), hash function (e.g. SHA512) and block mode (e.g. CBC).
Mechanisms also exist for generating keys, and deriving keys and parameters.

Objects and Attributes

An object is a piece of cryptographic information stored on a token.
Objects have a class (e.g. private key) , they also have a number of other attributes depending on their class.
There are three main classes of object:
  • keys (symmetric secret keys and asymmetric public and private keys)
  • domain parameters (storing the parameters used to generate keys)
  • certificates (e.g. X.509 certificates)

Keys

There are three classes of key objects:
  • symmetric secret keys;
  • asymmetric public keys;
  • asymmetric private keys.

Domain Parameters

Domain parameters are the parameters used to generate cryptographic keys (e.g. the name of the elliptic curve being used).
They are public information.

Sessions

Accessing a token is done by opening a session.
Sessions can be public or logged in.
Only a logged in session can access objects marked as private.

Concepts related to PKCS #11

Binary Formats and Padding

PKCS #11 is protocol agnostic and does not define or implement any codecs for the storing of enciphered data, keys, initialisation vectors, etc. outside the HSM.

PKCS #15

PKCS #15 defines a standard for storing cryptographic objects within the HSM device to enable interoperability between devices and tokens.
PKCS #15 is often referenced in conjunction with PKCS #11 as the storage format used on the tokens.

ASN.1, DER, BER

ASN.1 is a data model for storing structured information.
DER and BER are binary representations of that data model.

PEM

PEM is a standard for handling cryptographic objects. It is a base64 encoded version of the binary DER object.

Getting a Session

Cryptoki requires that an application open one or more sessions with a token to gain access to the token's objects and functions.
After the application opens a session, it has access to the token's public objects. All threads of a given application have access to exactly the same sessions and the same session objects.
To gain access to the token's private objects, the normal user must log in and be authenticated.

When a session is closed, any session objects which were created in that session are destroyed.
If a single application has multiple sessions open with a token, and it uses one of them to create a session object, then that session object is visible through any of that application's sessions. However, as soon as the session that was used to create the object is closed, that object is destroyed.

Generating Keys

Keys can either live for the lifetime of the session or be stored on the token.
Storing keys requires a read only session.

Symmetric Keys

  • AES
  • AES keys can be generated by specifying the key length.
  • DES2/3
  • DES2/3 keys are fixed length.

Asymmetric Keypairs

  • RSA
  • RSA keypairs can be generated by specifying the length of the modulus.
    The default public exponent is 65537.
  • DSA
  • DSA keypairs can be generated by specifying the length of the prime in bits.

From Domain Parameters

Domain parameters are often either specified by the requirements you are implementing for, or have a standard implementation to derive quality parameters.

  • DSA
  • DSA key pairs require three domain parameters: BASE, PRIME, SUBPRIME.
  • Diffie-Hellman
  • Elliptic Curve

Importing/Exporting Keys

It is best to only import/export public keys.

AES/DES

RSA

DSA

Elliptic Curve

X.509


PKCS #11 API

Making our application isolated from details of the underlying HSM, we need a standard API agreed by all HSM vendors in the market.
This where Public Key Cryptography Standard #11(PKCS #11) comes in to the picture.

The PKCS#11 standard specifies an application programming interface (API), called “Cryptoki,” for devices that hold cryptographic information and perform cryptographic functions.

PKCS#11 is a specification of the required set of rules and guidelines for the implementation of the API.

PKCS#11 defines the interface between an application and a cryptographic device.

PKCS #11 is a standard API specified by OASIS Open which is a global nonprofit organization .
OASIS Open provides only a set of ANSI C header files defining the interface exposed to client application.
HSM vendor is responsible for providing concrete implementation of the functionalities specified in PKCS #11.

  • Application directly speaks to the PKCS #11 API
  • API is responsible for calling the PKCS #11 module through C calls
  • the module speaks to the HSM via native calls
  • Module hand over the response from HSM to application through C interface implementation
The PKCS#11 presents to applications a common, logical view of the device called a “cryptographic token.
The following definitions apply to the PKCS#11 standards:
  • Cryptoki
  • The Cryptographic Token Interface defined in this standard.
    Cryptoki is a library (DLL or SO file) that is provided by the cryptographic device vendors.
    It contains an implementation of the PKCS#11 C header files.
    Every cryptographic device vendor provides its own PKCS#11 compliant library. Applications has to load this library in order to access the cryptographic device.
  • User
  • The person using an application that interfaces to Cryptoki.
  • Session
  • A logical connection between an application and a token.
    Once the session is in place, the application can perform different cryptographic operations with the token e.g. application can use the session object to generate asymmetric key pair, produce signature with the private key present inside the token and so on.
    When the application is done with the cryptographic operations then it can close the session with the token.
  • Slot
  • A logical reader(IO) that potentially contains a token.
    In case of HSMs, there could be hundreds or more slots are available.
    While in the case of smart cards, there could be only one slot available.
  • Token
  • The logical view of a cryptographic device defined by Cryptoki.
    Token is a device where application stores the cryptographic objects and also perform cryptographic operations.
    In the case of smart cards, you can think of slot as a smart card reader while the smart card inserted inside the reader is the token.
    In case of HSMs, when a slot is initialized in HSM then the token is present in the slot.
  • Object
  • An item that is stored on a token.
    May be data, a certificate, or a key.
Assume Crypto is an application which is using PKCS #11 supported HSM as it’s cryptographic provider.
If Crypto needs to generate an AES key using HSM and encrypt a sample of data using the generated key.
The following senarios is used:
  1. Crypto authenticates itself as user ‘USER’ to the HSM and creates a secure communication passage(ie. session between token and application) between device(ie. token resides within a slot) and Crypto.
  2. Crypto asks HSM to generate an AES key through the created communication passage(ie. session).
  3. HSM returns the created AES key through the passage.
  4. Crypto sends set of data needs to be encrypted with the encryption key through the safe passage.
  5. HSM sends back the ciphered data to the application through the communication passage.
  6. Crypto close the communication passage.
The similar secenario is used for most of the cryptographic operations, such as decryption, key generation, key saving, signing, hashing etc. with minor changes.

5 Functions

5.15 Functions for verifying signatures and MACs

The following functions for verifying signatures on data:
  • C_VerifyInit initializes a verification operation, where the signature is an appendix to the data.
  • After calling C_VerifyInit, the application can either call C_Verify to verify a signature on data in a single part; or call C_VerifyUpdate one or more times, followed by C_VerifyFinal, to verify a signature on data in multiple parts.
  • The verification operation MUST have been initialized with C_VerifyInit. A call to C_Verify always terminates the active verification operation.
    C_Verify cannot be used to terminate a multi-part operation, and MUST be called after C_VerifyInit without intervening C_VerifyUpdate calls.
  • C_VerifyUpdate continues a multiple-part verification operation, processing another data part.
  • C_VerifyFinal finishes a multiple-part verification operation, checking the signature.
The verification operation is active until the application calls C_Verify or C_VerifyFinal.
For most mechanisms, C_Verify is equivalent to a sequence of C_VerifyUpdate operations followed by C_VerifyFinal.

5.16 Message-based functions for verifying signatures and MACs

Message-based verification refers to the process of verifying signatures on multiple messages using the same verification mechanism and verification key.

  • C_VerifyMessage verifies a signature on a message in a single part operation, where the signature is an appendix to the data.
  • C_MessageVerifyInit must previously been called on the session.
  • The message-based verification process MUST have been initialized with C_MessageVerifyInit.
A call to C_VerifyMessage starts and terminates a message verification operation.
C_VerifyMessage does not finish the message-based verification process. Additional C_VerifyMessage or C_VerifyMessageBegin and C_VerifyMessageNext calls may be made on the session.
After calling C_MessageVerifyInit, the application can either call C_VerifyMessage to verify a signature on a message in a single part; or call C_VerifyMessageBegin, followed by C_VerifyMessageNext one or more times, to verify a signature on a message in multiple parts. This may be repeated several times.
The message-based verification process is active until the application calls C_MessageVerifyFinal to finish the message-based verification process.

For most mechanisms, C_VerifyMessage is equivalent to C_VerifyMessageBegin followed by a sequence of C_VerifyMessageNext operations.

留言

熱門文章