Showing posts with label OpenSC. Show all posts
Showing posts with label OpenSC. Show all posts

Encrypting files using AES keys on SmartCard HSM or Nitrokey HSM2 without key derivation

Table of Contents

  1. Overview
  2. Prerequisites
  3. Installation
  4. Configuration
  5. AES Key Generation
  6. Testing AES Keys
  7. Encryption/Decryption Scripts
  8. Usage Examples
  9. Important Notes
  10. Troubleshooting
  11. Security Considerations
  12. Conclusion

Overview

This guide explains how to use AES keys with your SmartCard HSM (Identiv uTrust 3512) for encryption and decryption operations.

What This Guide Covers

Primary Use Cases:

  • File Encryption/Decryption: Encrypt and decrypt files using AES keys stored on the SmartCard HSM. Files are transferred to the HSM token where encryption/decryption operations are performed, ensuring no sensitive data remains on the host system.
  • Data Protection: Secure sensitive data with hardware-backed AES encryption
  • Key Management: Generate, store, and manage AES keys on the HSM token
  • Multi-Token Deployment: Export and import AES keys across multiple SmartCard HSM tokens

Supported Operations:

  • AES-CBC encryption and decryption
  • AES-CMAC message authentication
  • Key wrapping and unwrapping
  • Key derivation (SP800-56C)

What This Guide Does NOT Cover:

  • RSA or ECC key operations (different guide)
  • Key derivation for file encryption
  • SSH key management (different use case)
  • Certificate operations (separate topic)

Target Applications:

  • Data at Rest Protection: Secure storage of sensitive files and databases with hardware-backed encryption
  • Secure file storage and transmission
  • Database encryption
  • Application-level data protection
  • Compliance requirements (FIPS, Common Criteria)

[WARNING] CRITICAL SECURITY WARNING: Before using AES keys on your SmartCard HSM, you must verify your firmware version. SmartCard HSM devices with firmware versions 3.1 and 3.2 have a critical bug that generates weak AES keys with little to no entropy. These keys must be considered broken and should not be used for any security operations. Read the advisory.

Required Action: SmartCard HSM and Nitrokey HSM2 - Update to firmware version 3.3 or later via the PKI-as-a-Service Portal before generating or using AES keys.

Note: RSA and ECC keys are not affected by this bug. Only AES key generation is impacted.

Prerequisites

Hardware Requirements

  • SmartCard HSM (Identiv uTrust 3512) with firmware version 3.3 or later
  • CCID-compatible card reader
  • USB connection

Software Requirements

  • Linux with PC/SC support
  • SmartCard HSM PKCS#11 library (MANDATORY) - OpenSC PKCS#11 library cannot detect or use AES keys on the token
  • OpenSC tools (pkcs11-tool)
  • SmartCard Shell3 (for AES key generation)

Firmware Verification

Before proceeding, verify your SmartCard HSM firmware version:

pkcs11-tool --module "/home/user/bin/sc-hsm-embedded-2.12/lib/libsc-hsm-pkcs11.so" \
    --show-info

Look for the firmware version in the output. If it shows version 3.1 or 3.2, you must update before using AES keys.

Installation

1. Install Development Tools

# Install development tools
sudo dnf groupinstall "Development Tools"
sudo dnf install autoconf automake libtool
sudo dnf install pcsc-lite-devel

2. Download and Compile SmartCard HSM PKCS#11 Library

[WARNING] CRITICAL: The SmartCard HSM PKCS#11 library is MANDATORY for AES key operations. The standard OpenSC PKCS#11 library cannot detect or use AES keys stored on the SmartCard HSM token.

# Download from GitHub releases
cd /tmp
wget https://github.com/CardContact/sc-hsm-embedded/releases/download/v2.12/\
    sc-hsm-embedded-2.12.tar.gz
tar -xzf sc-hsm-embedded-2.12.tar.gz
cd sc-hsm-embedded-2.12

# Configure and compile
autoreconf -fi
./configure --prefix=/home/user/bin/sc-hsm-embedded-2.12
make
make check
make install

Configuration

Environment Variables

# Set the module path
export SC_HSM_MODULE="/home/user/bin/sc-hsm-embedded-2.12/lib/libsc-hsm-pkcs11.so"
export HSM_SLOT=1

Token Detection

Verify your SmartCard HSM is detected using the SmartCard HSM PKCS#11 library (not OpenSC):

pkcs11-tool --module "/home/user/bin/sc-hsm-embedded-2.12/lib/libsc-hsm-pkcs11.so" \
    --list-token-slots

Expected output:

Available slots:
Slot 0 (0x1): Identiv uTrust 3512 SAM slot Token [CCID Interface] (55512030605)
  token label        : [REDACTED]-HISEC-1
  token manufacturer : CardContact (www.cardcontact.de)
  token model        : SmartCard-HSM
  token flags        : login required, rng, token initialized, PIN initialized

AES Key Generation

Important Note: AES Key Generation Method

AES keys on SmartCard HSM are generated and stored using SmartCard Shell3 software, not through direct PKCS#11 operations. The SmartCard Shell3 provides the interface for creating AES keys on the HSM token.

SmartCard Shell3 Requirements

  • GUI Version: SmartCard Shell3 GUI (scsh3gui) is the primary method for AES key generation
  • CLI Version: SmartCard Shell3 CLI (scsh3) has known card detection issues (see separate documentation)
  • Key Management: Keys are created through the SmartCard Shell3 Key Manager interface

Key Generation Process

  1. Launch SmartCard Shell3 GUI:
    cd /home/user/CardContact/scsh/scsh-3.18.55/
    ./scsh3gui
    
  2. Authenticate to the HSM:
    • Select your SmartCard HSM token
    • Enter your User PIN when prompted
  3. Access Key Manager:
    • Navigate to the Key Manager in the SmartCard Shell3 interface
    • Right-click on the appropriate key domain (e.g., DKEK share)
  4. Generate AES Key (presumably on the DKEK share):
    • Select "Generate Key" → "AES"
    • Choose key size (128, 192, or 256 bits)
    • Provide a label for the key
    • Select algorithms (AES-CBC, AES-CMAC, etc.)

Exporting AES Keys for Multiple Tokens

If you need to use the same AES key across multiple SmartCard HSM tokens that share the same DKEK, you can export the key:

  1. In the SmartCard Shell3 GUI, click on the AES key object in the list (PIN required)
  2. Right-click on the key and select "Wrap Key (and Certificate)"
  3. Save the key as a *.wky file
  4. Import the *.wky file on other tokens with the same DKEK share

Verifying Generated Keys

After generating AES keys via SmartCard Shell3, you can verify them using PKCS#11 tools, as shown below.

Testing AES Keys

List All AES Keys

Use the following script to list all AES keys on your token:

[WARNING] IMPORTANT: You may need to modify the following variables in the script to match your setup:

  • HSM_SLOT: The slot number where your SmartCard HSM is detected
  • SC_HSM_MODULE: Path to your SmartCard HSM PKCS#11 library

Save this script as list_aes_keys.sh:

#!/bin/bash
# list_aes_keys.sh

set -e

# Configuration
SC_HSM_MODULE="/home/user/bin/sc-hsm-embedded-2.12/lib/libsc-hsm-pkcs11.so"
HSM_SLOT=1

echo "=== AES Keys on SmartCard HSM ==="
echo "Library: $SC_HSM_MODULE"
echo "Slot: $HSM_SLOT"
echo

echo "Please enter your SmartCard HSM PIN when prompted:"

# List all secret key objects
echo "=== All Secret Key Objects ==="
pkcs11-tool --module "$SC_HSM_MODULE" \
    --slot $HSM_SLOT \
    --login \
    --list-objects \
    --type secrkey

echo
echo "=== Summary ==="
echo "The above shows all secret key objects on your SmartCard HSM token."
echo "Look for entries starting with 'Secret Key Object; AES' to find AES keys."
echo "Each AES key will show:"
echo "- Label (name)"
echo "- ID (unique identifier)"
echo "- Usage (encrypt, decrypt)"
echo "- Access (security attributes)"
echo

Usage:

chmod +x list_aes_keys.sh
./list_aes_keys.sh

Expected Output:

Secret Key Object; AES length 32
  label:      AES-1
  ID:         b20ba7e28e29c90f
  Usage:      encrypt, decrypt
  Access:     sensitive, always sensitive, never extractable, local
Secret Key Object; AES length 32
  label:      AES-2
  ID:         4eaa8024a063e8b6
  Usage:      encrypt, decrypt
  Access:     sensitive, always sensitive, never extractable, local

Encryption/Decryption Scripts

Simple AES Encryption Test

Save this script as aes_encrypt_simple.sh:

#!/bin/bash
# aes_encrypt_simple.sh

set -e

# Configuration
# [WARNING] IMPORTANT: Modify these variables to match your setup
SC_HSM_MODULE="/home/user/bin/sc-hsm-embedded-2.12/lib/libsc-hsm-pkcs11.so"
HSM_SLOT=1
AES_KEY_ID="b20ba7e28e29c90f"  # Use the ID from your AES key

echo "=== Simple AES-1 Encryption Test ==="
echo "Library: $SC_HSM_MODULE"
echo "Slot: $HSM_SLOT"
echo "Key ID: $AES_KEY_ID"
echo

# Create a test file with exactly 16 bytes (AES block size)
echo "Creating test data..."
echo -n "1234567890123456" > test_block.txt
echo "[INFO] Created test file with 16 bytes (AES block size)"

# Generate IV
echo "Generating IV..."
openssl rand -hex 16 > iv.txt
IV=$(cat iv.txt)
echo "[INFO] IV: $IV"

echo
echo "=== Attempting AES-CBC Encryption ==="
echo "Please enter your SmartCard HSM PIN when prompted:"

# Try encryption with the exact block size
pkcs11-tool --module "$SC_HSM_MODULE" \
    --slot $HSM_SLOT \
    --login \
    --encrypt \
    --mechanism AES-CBC \
    --iv "$IV" \
    --input-file test_block.txt \
    --output-file test_block.enc \
    --id "$AES_KEY_ID"

if [ $? -eq 0 ]; then
    echo "[SUCCESS] Encryption completed!"
    echo "[INFO] Encrypted file: test_block.enc"
    echo "[INFO] IV saved to: iv.txt"
else
    echo "[ERROR] Encryption failed"
fi

echo
echo "=== Test Complete ==="

Simple AES Decryption Test

Save this script as aes_decrypt_simple.sh:

#!/bin/bash
# aes_decrypt_simple.sh

set -e

# Configuration
# [WARNING] IMPORTANT: Modify these variables to match your setup
SC_HSM_MODULE="/home/user/bin/sc-hsm-embedded-2.12/lib/libsc-hsm-pkcs11.so"
HSM_SLOT=1
AES_KEY_ID="b20ba7e28e29c90f"  # Use the ID from your AES key

echo "=== Simple AES-1 Decryption Test ==="
echo "Library: $SC_HSM_MODULE"
echo "Slot: $HSM_SLOT"
echo "Key ID: $AES_KEY_ID"
echo

# Check if encrypted file exists
if [ ! -f test_block.enc ]; then
    echo "[ERROR] Encrypted file not found: test_block.enc"
    echo "Please run aes_encrypt_simple.sh first"
    exit 1
fi

# Check if IV file exists
if [ ! -f iv.txt ]; then
    echo "[ERROR] IV file not found: iv.txt"
    echo "Please run aes_encrypt_simple.sh first"
    exit 1
fi

IV=$(cat iv.txt)
echo "[INFO] Using IV: $IV"

echo
echo "=== Attempting AES-CBC Decryption ==="
echo "Please enter your SmartCard HSM PIN when prompted:"

# Try decryption
pkcs11-tool --module "$SC_HSM_MODULE" \
    --slot $HSM_SLOT \
    --login \
    --decrypt \
    --mechanism AES-CBC \
    --iv "$IV" \
    --input-file test_block.enc \
    --output-file test_block.dec \
    --id "$AES_KEY_ID"

if [ $? -eq 0 ]; then
    echo "[SUCCESS] Decryption completed!"
    echo "[INFO] Decrypted file: test_block.dec"
    
    # Verify decryption
    if diff test_block.txt test_block.dec > /dev/null; then
        echo "[SUCCESS] Decryption verified - files match!"
    else
        echo "[ERROR] Decryption failed - files don't match"
    fi
else
    echo "[ERROR] Decryption failed"
fi

echo
echo "=== Test Complete ==="

Complete AES Key Usage Script

Save this script as aes_encrypt_decrypt.sh:

#!/bin/bash

# Use the AES-1 key on SmartCard HSM for encryption/decryption
# The key was found with the new SmartCard HSM PKCS#11 library

set -e

# Configuration
# [WARNING] IMPORTANT: Modify these variables to match your setup
SC_HSM_MODULE="/home/user/bin/sc-hsm-embedded-2.12/lib/libsc-hsm-pkcs11.so"
HSM_SLOT=1
AES_KEY_LABEL="AES-1"  # Use the label from your AES key
AES_KEY_ID="b20ba7e28e29c90f"  # Use the ID from your AES key

echo "=== Using AES-1 Key on SmartCard HSM ==="
echo "Library: $SC_HSM_MODULE"
echo "Slot: $HSM_SLOT"
echo "Key Label: $AES_KEY_LABEL"
echo "Key ID: $AES_KEY_ID"
echo

# Function to encrypt a file using AES-1 key
encrypt_file() {
    local input_file="$1"
    local output_file="$2"
    
    echo "=== Encrypting with AES-1 Key ==="
    echo "Input: $input_file"
    echo "Output: $output_file"
    echo "Please enter your SmartCard HSM PIN when prompted:"
    
    # Generate a random IV (16 bytes for AES)
    echo "[INFO] Generating random IV..."
    openssl rand -hex 16 > iv.txt
    IV=$(cat iv.txt)
    echo "[INFO] IV: $IV"
    
    # Use AES-CBC encryption with the AES-1 key and IV
    pkcs11-tool --module "$SC_HSM_MODULE" \
        --slot $HSM_SLOT \
        --login \
        --encrypt \
        --mechanism AES-CBC \
        --iv "$IV" \
        --input-file "$input_file" \
        --output-file "$output_file" \
        --id "$AES_KEY_ID"
    
    if [ $? -eq 0 ]; then
        echo "[SUCCESS] File encrypted successfully"
        echo "[INFO] IV saved to iv.txt for decryption"
    else
        echo "[ERROR] Encryption failed"
        rm -f iv.txt
        return 1
    fi
}

# Function to decrypt a file using AES-1 key
decrypt_file() {
    local input_file="$1"
    local output_file="$2"
    local iv_file="${3:-iv.txt}"
    
    echo "=== Decrypting with AES-1 Key ==="
    echo "Input: $input_file"
    echo "Output: $output_file"
    echo "IV file: $iv_file"
    echo "Please enter your SmartCard HSM PIN when prompted:"
    
    if [ ! -f "$iv_file" ]; then
        echo "[ERROR] IV file not found: $iv_file"
        echo "Please provide the IV used for encryption"
        return 1
    fi
    
    IV=$(cat "$iv_file")
    echo "[INFO] Using IV: $IV"
    
    # Use AES-CBC decryption with the AES-1 key and IV
    pkcs11-tool --module "$SC_HSM_MODULE" \
        --slot $HSM_SLOT \
        --login \
        --decrypt \
        --mechanism AES-CBC \
        --iv "$IV" \
        --input-file "$input_file" \
        --output-file "$output_file" \
        --id "$AES_KEY_ID"
    
    if [ $? -eq 0 ]; then
        echo "[SUCCESS] File decrypted successfully"
    else
        echo "[ERROR] Decryption failed"
        return 1
    fi
}

# Function to test the AES-1 key with a simple operation
test_aes1_key() {
    echo "=== Testing AES-1 Key ==="
    echo "Please enter your SmartCard HSM PIN when prompted:"
    
    # Try to get key info
    pkcs11-tool --module "$SC_HSM_MODULE" \
        --slot $HSM_SLOT \
        --login \
        --list-objects \
        --type secrkey \
        --id "$AES_KEY_ID"
}

# Function to show usage
show_usage() {
    echo "Usage: $0 {encrypt|decrypt|test} [ ]"
    echo
    echo "Examples:"
    echo "  $0 test                           # Test AES-1 key"
    echo "  $0 encrypt test.txt test.txt.enc  # Encrypt file"
    echo "  $0 decrypt test.txt.enc test.txt.dec [iv.txt]  # Decrypt file"
    echo
    echo "The script uses the AES-1 key stored on your SmartCard HSM"
    echo "for AES-CBC encryption/decryption operations."
}

# Main script logic
case "${1:-}" in
    encrypt)
        if [ $# -ne 3 ]; then
            echo "[ERROR] Usage: $0 encrypt  "
            exit 1
        fi
        encrypt_file "$2" "$3"
        ;;
    decrypt)
        if [ $# -lt 3 ] || [ $# -gt 4 ]; then
            echo "[ERROR] Usage: $0 decrypt   [iv_file]"
            exit 1
        fi
        decrypt_file "$2" "$3" "${4:-}"
        ;;
    test)
        test_aes1_key
        ;;
    *)
        show_usage
        exit 1
        ;;
esac

echo
echo "=== Operation Complete ==="

Usage Examples

1. List AES Keys

./list_aes_keys.sh

2. Test Simple Encryption/Decryption

# Encrypt
./aes_encrypt_simple.sh

# Decrypt
./aes_decrypt_simple.sh

3. Use Complete Script

# Test key
./aes_encrypt_decrypt.sh test

# Encrypt file
./aes_encrypt_decrypt.sh encrypt myfile.txt myfile.txt.enc

# Decrypt file
./aes_encrypt_decrypt.sh decrypt myfile.txt.enc myfile.txt.dec

Important Notes

Data Requirements

  • Block Size: Data must be padded to AES block size (16 bytes)
  • IV Required: CBC mode requires an Initialization Vector
  • PIN Authentication: All operations require SmartCard HSM PIN

Security Features

  • Hardware Protection: Keys never leave the HSM in plaintext
  • PIN Protection: All operations require authentication
  • Key Export: Keys can be exported only between tokens sharing the same DKEK share

Supported Operations

  • AES-CBC Encryption/Decryption
  • AES-CMAC Signing
  • AES Key Generation (via SmartCard Shell3 GUI only)

Firmware Security Considerations

[WARNING] Critical HSM Firmware Bug (Versions 3.1-3.2):

  • SmartCard HSM and Nitrokey HSM2 devices with firmware versions 3.1 and 3.2 generate weak AES keys. Read the advisory.
  • These keys have little to no entropy and must be considered broken
  • Impact: Only affects AES key generation, not RSA or ECC keys
  • Solution: Be sure the tokens are running the latest firmware version. Check if newer version is available at PKI-as-a-Service-Portal, and install it before generating or using AES keys.

Update Process:

  1. Register an account at CardContact Developer Network (CDN)
  2. Create a firmware update request
  3. Select "Current token in reader" and submit
  4. Follow the portal instructions for the update process
  5. Important: All keys must be removed before firmware update
  6. After update, reinitialize the device and restore keys

Troubleshooting

Common Issues

  1. "CKR_FUNCTION_NOT_SUPPORTED"
    • Ensure data is padded to 16-byte blocks
    • Use exact block size for testing
  2. "CKR_USER_NOT_LOGGED_IN"
    • Enter PIN when prompted
    • Don't redirect output during PIN prompts
  3. "CKR_SLOT_ID_INVALID"
    • Use slot 1 instead of slot 0
    • Verify token is present

Security Considerations

Direct AES Storage vs Key Derivation

Aspect Direct AES Storage HSM Key Derivation
Key Storage AES key stored on HSM Salt stored on disk, key derived on-demand
Intermediate Data None Salt file, derived key file
Cold Boot Vulnerability Low (no temp files) Medium (temp files on disk)
Performance Fast (direct operations) Slower (derivation + operation)
Flexibility Fixed key Variable key from passphrase

Best Practices

  1. Authentication: Always authenticate before operations
  2. Data Padding: Ensure data fits AES block requirements
  3. IV Management: Use random IVs and store them securely
  4. Error Handling: Check return codes and handle failures
  5. Cleanup: Remove temporary files securely

Conclusion

This guide provides a complete workflow for using AES keys with your SmartCard HSM. The approach offers hardware-level security with direct AES operations, making it suitable for high-security applications where key protection is critical.

Technical Summary

  1. AES Key Generation: SmartCard Shell3 GUI required for key generation; PKCS#11 direct operations not supported
  2. Firmware Security: Version 3.3+ mandatory due to weak key generation vulnerability in versions 3.1-3.2
  3. Security Architecture: Hardware-protected AES keys with mandatory PIN authentication for all operations
  4. CLI Implementation: SmartCard Shell3 CLI exhibits card detection failures due to initialization sequence differences
  5. Firmware Update Protocol: Requires complete key removal and device reinitialization post-update

Using SmartCard-HSM 4K USB-Token to work with ECDSA keys in RHEL, CentOS, and Enterprise Linux, versions 7 and 8

Content:

1. Introduction

2. Connecting the device

3. Downloading, compiling, and installing the last stable release of OpenSC and HSM code

4. Initializing the device (setting the PINs)

5. Generating 521-bit EC key pair

6. Using the USB token as OpenSSL PKCS#11 engine

7. Generating CSR, based on a key pair previously stored in the token, through OpenSSL PKCS#11 engine

8. Importing X.509 certificate to the token storage

 

1. Introduction

In the modern cryptographic systems, the use of Elliptic Curve cryptography (ECC) becomes de facto a standard. Meanwhile, even now (it is 2019), it is quite rare to find a cryptographic token that supports the generation and use of ECDSA keys, up to 512 bits, SHA512 hash function (embedded in the processor of the token), and comes with a driver for Linux OS support. Most of the available tokens support mostly RSA key pairs, and even if they support ECDSA, that support is partial and the maximum key size is limited bellow 512 bits.

Surprisingly, you can find a reliable crypto token, that supports ECDSA 512-bit keys and SHA512 at:

cardomatic.de

The SmartCard-HSM 4K USB-Token, they have in sale, is supported by the driver library libccid.so, which is part of the OpenSC package (version 0.16 or higher). If one can download, compile, and install locally both the latest OpenSC and HSM code release, that is sufficient to employ the SmartCard-HSM 4K USB-Token in OpenSSL (as an engine), Mozilla Firefox, and Mozilla Thunderbird (as a security device).

The notes given bellow explain how to make the SmartCard-HSM 4K USB-Token device available in a Linux-based system running CentOS 7, Scientific Linux 7, Red Hat Enterprise Linux 8, and (possibly) Red Hat Enterprise Linux 8, how initializing the device, and the modules to interact the opensc tools (like pkcs11-tools and pkcs15-tools).

 

2. Connecting the device

Install the following packages (there is a good chance they are already installed):

# yum install pcsc pcsc-lite-ccid opensc

Enable the daemon pcscd to be loaded when starting/restarting the system:

# systemctl enable pcscd

and run it manually afterwards:

# systemctl start pcscd

Now you can connect the SmartCard-HSM 4K USB-Token device to the system. Records like those given bellow will be added to the /var/log/messages by syslog:

May 10 15:00:06 argus kernel: usb 3-10: new full-speed USB device number 9 using xhci_hcd
May 10 15:00:06 argus kernel: usb 3-10: New USB device found, idVendor=04e6, idProduct=5816
May 10 15:00:06 argus kernel: usb 3-10: New USB device strings: Mfr=1, Product=2, SerialNumber=5
May 10 15:00:06 argus kernel: usb 3-10: Product: uTrust 3512 SAM slot Token
May 10 15:00:06 argus kernel: usb 3-10: Manufacturer: Identiv
May 10 15:00:06 argus kernel: usb 3-10: SerialNumber: 55511247701280

Their appearance there does not exactly mean the device is accessible by the applications. It only indicates that the USB device is properly recognized by libusb. In addition, the device will appear under the Vendor Name: SCM Microsystems, Inc., Vendor ID: 04e6, and Product ID: 5816, in the output generated by the execution of lsusb:

Bus 003 Device 009: ID 04e6:5816 SCM Microsystems, Inc.

If detailed debugging information, regarding the process of device detection, performed by pcscd daemon, is required, do modify the content of the file /usr/lib/systemd/system/pcscd.service (used by systemd to invoke the daemon pcscd), by adding the additional declaration --debug to the end of the line starting with "ExecStart":

ExecStart=/usr/sbin/pcscd --foreground --auto-exit --debug

Save the changes to the file, load the new list of declarations:

# systemctl daemon-reload

and finally restart the daemon pcscd:

# systemctl restart pcscd

At that moment, start monitoring the new content appended to the file /var/log/messages (# tailf /var/log/messages will do), then unplug and plug in the device, and watch what kind of messages the syslog daemon is appending to the file.

To prevent the fast growth of the /var/log/messages size on the disk, immediately after finishing with the analysis of the debug information, do restore the original declarations in /usr/lib/systemd/system/pcscd.service (remove the additional declaration --debug), reload it, and restart the daemon pcscd!

 

3. Downloading, compiling, and installing the last stable release of OpenSC and HSM code

First, install the required RPM packages (if they are not already installed):

# yum install git gcc gcc-c++ make

Then fetch the code of sc-hsm-embedded project, hosted on Github, configure, compile, and install it (change the destination folder after --prefix, if needed):

$ git clone https://github.com/CardContact/sc-hsm-embedded.git
$ cd sc-hsm-embedded
$ ./configure --prefix=/usr/local/sc-hsm-embedded
$ make
$ sudo make install

General note: Red Hat Enterprise Linux 8 (as well as CentOS 8 and Scientific Linux 8), ships OpenSC version 0.19. That means one does not need to compile OpenSC code, as explained bellow, in systems running EL8.

Once the installation is successfully completed, download, compile, and install the latest stable release of the OpenSC code (change the destination folder after --prefix and --with-completiondir, if needed):

$ wget https://github.com/OpenSC/OpenSC/releases/download/0.19.0/opensc-0.19.0.tar.gz
$ tar xvf opensc-0.19.0.tar.gz
$ cd opensc-0.19.0
$ ./configure --prefix=/usr/local/opensc-0.19.0 --with-completiondir=/usr/local/opensc-0.19.0/share/bash-completion/completions
$ make
$ sudo make install

The next step is to add the folders containing the installed binaries and libraries to the user's PATH and LD_LIBRARY_PATH environmental variables. Those additions can be made either system-wide (available to all users, inclusive) or user-specific (available only to specific users, exclusive):

  • system-wide:

    Write down the following export declarations:

    export PATH=/usr/local/opensc-0.19.0/bin:$PATH
    export LD_LIBRARY_PATH=/usr/local/sc-hsm-embedded/lib:/usr/local/opensc-0.19.0/lib:$LD_LIBRARY_PATH

    to the file /etc/profile.d/opensc.sh (create the file, it does not exist by default there).

  • user-specific:

    Open each ~/.bashrc file and append (to the end) the following lines:

    export PATH=/usr/local/opensc-0.19.0/bin:$PATH
    export LD_LIBRARY_PATH=/usr/local/sc-hsm-embedded/lib:/usr/local/opensc-0.19.0/lib:$LD_LIBRARY_PATH

 

4. Initializing the device (setting the PINs)

The SmartCard-HSM 4K USB-Token device comes uninitialized! That means the device cannot be used, unless complete the initialization process first.

Connect the token to the system and invoke the tool sc-hsm-tool by specifying the SO PIN (SO stands for "Security Officer", change SO PIN 3537363231383830, specified in the example bellow, with another unique 16-digit long decimal number and do not forget it) and the user's PIN (change 123456 to another number):

$ sc-hsm-tool --initialize --so-pin 3537363231383830 --pin 123456

Here, the number after --so-pin is the SO PIN and the one after --pin is the user's PIN. Note that the SO PIN is the most important PIN, for it allows write access to the all slots of the device storage. Also, it can change every PUK and PIN, previously stored there (that includes the SO PIN itself). So do not loose SO PIN number!


5. Generating 521-bit EC key pair

Invoke the tool pkcs11-tool and specify the key type (EC:specp521r1 for 521-bit EC encryption key) and key pair ID label (it helps later to access the keys):

$ pkcs11-tool --module libsc-hsm-pkcs11.so -l --keypairgen --key-type EC:secp521r1 --id 10 --label "EC pair ID 10"

The user's PIN will be requested next, to grant access to the device storage and processor:

Enter PKCS#11 token PIN for SmartCard-HSM:

If the provided user's PIN is correct, it will take up to 2-3 seconds to execute and complete the key generation process.

The most important part of the command line above is the ID number assigned to the key pair (given above is 10, but you may reserve some other number, including hexadecimal number syntax, which is not already taken), because from that moment onward, the keys of that pair can be selected and involved in operations only if their ID number is specified.

 

6. Using the USB token as OpenSSL PKCS#11 engine

Install the package openssl-pkcs11 to enable the OpenSSL PKCS#11 engines functionality:

# yum install openssl-pkcs11

After that, store the following minimal OpenSSL configuration into a local file (openssl_hsm.cnf, for the sake of our illustration process):

openssl_conf = openssl_def

[openssl_def]
engines = engine_section

[engine_section]
pkcs11 = pkcs11_section

[pkcs11_section]
engine_id = libsc-hsm-pkcs11
dynamic_path = /usr/lib64/engines-1.1/pkcs11.so
MODULE_PATH = /usr/local/opensc-0.19.0/lib/libsc-hsm-pkcs11.so
init = 0


[ req ]
distinguished_name      = req_distinguished_name
string_mask = utf8only

[ req_distinguished_name ]

The only declaration in openssl_hsm.cnf one might need to change is that of MODULE_PATH:

MODULE_PATH = /usr/local/opensc-0.19.0/lib/libsc-hsm-pkcs11.so

Replace /usr/local/opensc-0.19.0 there with the actual folder, where the file libsc-hsm-pkcs11.so is stored. Note that the file is brought there during the installation of the HSM code).

 

7. Generating CSR, based on a key pair previously stored in the token, through OpenSSL PKCS#11 engine

If the OpenSSL PKCS#11 engine configuration file is available, the generation of CSR PKCS#10 block requires to specify the key pair ID (that is the number assigned to the key pair during the process of key pair generation):

$ openssl req -new -subj "/CN=server.example.com" -out request.pem -sha512 -config openssl_hsm.cnf -engine pkcs11 -keyform engine -key 10

One can expand both command line arguments and the set of declarations stored in openssl_hsm.cnf, if the CSR should contain some specific extensions, requested by the certificate issuer.

 

8. Importing X.509 certificate to the token storage

That type of operation is possible only if the X.509 certificate is stored in DER format (binary). For example, if the file SU_ECC_Root_CA.crt contains PEM formatted X.509 certificate, that certificate might be converted into DER format, by using openssl:

$ openssl x509 -in SU_ECC_Root_CA.crt -outform DER -out SU_ECC_Root_CA.der

To import the DER formatted X.509 certificate to the USB storage token, use the tool pkcs11-tool:

$ pkcs11-tool --module ibsc-hsm-pkcs11.so --login --write-object SU_ECC_Root_CA.der --type cert --id `uuidgen | tr -d -` --label "SU_ECC_ROOT_CA"

The label string after --label, naming the X.509 certificate, should be specified in a way hinting the purpose of having and using that certificate.


Creative Commons - Attribution 2.5 Generic. Powered by Blogger.

Implementing LUKS Encryption on Software RAID Arrays with LVM2 Management

A comprehensive guide to partition-level encryption for maximum security ...

Search This Blog

Translate