Skip to content

PKI (Public Key Infrastructure) in OT – with solutions

Exercice 1 : Checking a 1st certificate

Take a known site and check its validity. For instance, go to https://www.deepl.com/ and check out:

  • Certificate validity
  • Extended Key Usage
  • Number of binary forms a certificate can be retrieved and analyzed
  • Find the SHA1 fingerprint in the exported certificate

Is this according to your expectations as far as a commercial company is concerned?

Solution

The responses for Deepl are :

  • although it is a commercial solution, Let’s Encrypt is used
  • the certificate is valid until June 26th 2025 (written on April 8th, 2025)
  • Extended Key Usage is defined as “Server Authentication, Client Authentication
  • Forms can be:

    • PEM (Privacy-enhanced Electronic Mail), Base 64, Prefix —BEGIN…)
    • DER (Distinguished Encoding Rules)
    • PKCS developed by RSA laboratories
    • PKCS#1: RSA encryption standard
    • PKCS#5: Password-Based Encryption Standard
    • PKCS#7: Cryptographic Message Syntax Standard
    • PKCS#8: Private-key Information Syntax Standard
    • PKCS#10: Certification Request Syntax Standard
    • PKCS#12: Personal Information Exchange Syntax Standard
  • FB:3D:E5:9E:47:A6:68:61:DE:39:90:23:56:D2:2B:E7:95:7C:B0:2B (SHA-1)

Here the downloaded pem certificate (openssl x509 -in <certificate_file>.pem -text -noout):

Certificate:
Data:
    Version: 3 (0x2)
    Serial Number:
        05:44:2c:95:cb:ed:55:7b:09:2f:f4:1c:27:23:9a:c1:c5:af
    Signature Algorithm: sha256WithRSAEncryption
    Issuer: C=US, O=Let's Encrypt, CN=R11
    Validity
        Not Before: Mar 28 18:20:50 2025 GMT
        Not After : Jun 26 18:20:49 2025 GMT
    Subject: CN=www.deepl.com
    Subject Public Key Info:
        Public Key Algorithm: rsaEncryption
            Public-Key: (2048 bit)
            Modulus:
                00:b8:6d:eb:93:91:12:bc:3a:ce:9c:7c:46:fd:7a:
                39:e5:21:60:87:ea:fa:c0:43:9d:02:ff:1b:b1:20:
                b2:ff:00:d6:e7:42:3a:74:a7:b5:38:49:77:21:b5:
                fc:e4:06:72:ab:a8:a7:cf:21:b4:84:ec:88:5d:2f:
                b7:fa:5c:b4:4a:8b:b4:39:17:e8:ed:2c:c0:73:30:
                ff:79:60:fc:4a:fd:0a:77:75:9e:a6:e6:64:b0:4b:
                d0:0f:e8:10:b4:b1:d3:8e:2a:1e:44:6e:06:1b:65:
                0f:41:de:df:5e:f9:79:62:bb:39:3e:55:31:b4:5a:
                74:b3:25:b8:1b:19:3d:18:5c:89:d1:11:bf:4c:57:
                ef:a6:d1:f5:da:66:e2:d6:75:9b:7b:c5:f5:96:72:
                f4:a2:c8:d1:0c:a2:73:42:05:f7:79:28:54:68:4e:
                70:cf:83:57:eb:c9:1f:e9:d9:ff:09:e5:c9:5e:32:
                69:e2:ae:85:f2:fb:e3:d7:50:52:a5:57:20:64:d4:
                5e:d1:a8:e3:2a:87:0c:f5:02:a5:ef:f1:c7:a4:d1:
                b0:44:00:9c:76:a3:eb:c2:c7:c3:dc:d9:1a:55:0d:
                5c:f6:4e:5a:19:29:c5:64:5e:b4:74:a7:67:58:eb:
                39:61:83:27:da:fc:7e:a0:02:61:59:b7:f8:99:1a:
                5d:03
            Exponent: 65537 (0x10001)
    X509v3 extensions:
        X509v3 Key Usage: critical
            Digital Signature, Key Encipherment
        X509v3 Extended Key Usage:
            TLS Web Server Authentication, TLS Web Client Authentication
        X509v3 Basic Constraints: critical
            CA:FALSE
        X509v3 Subject Key Identifier:
            A2:48:88:BB:92:92:B4:BB:59:1C:50:73:21:08:CC:BA:FF:EC:8D:4C
        X509v3 Authority Key Identifier:
            C5:CF:46:A4:EA:F4:C3:C0:7A:6C:95:C4:2D:B0:5E:92:2F:26:E3:B9
        Authority Information Access:
            OCSP - URI:http://r11.o.lencr.org
            CA Issuers - URI:http://r11.i.lencr.org/
        X509v3 Subject Alternative Name:
            DNS:*.www.deepl.com, DNS:www.deepl.com
        X509v3 Certificate Policies:
            Policy: 2.23.140.1.2.1
        X509v3 CRL Distribution Points:
            Full Name:
              URI:http://r11.c.lencr.org/48.crl

        CT Precertificate SCTs:
            Signed Certificate Timestamp:
                Version   : v1 (0x0)
                Log ID    : 4E:75:A3:27:5C:9A:10:C3:38:5B:6C:D4:DF:3F:52:EB:
                            1D:F0:E0:8E:1B:8D:69:C0:B1:FA:64:B1:62:9A:39:DF
                Timestamp : Mar 28 19:19:20.713 2025 GMT
                Extensions: none
                Signature : ecdsa-with-SHA256
                            30:45:02:20:76:5C:D3:EC:13:33:B7:93:78:A1:55:5E:
                            2B:3F:57:F0:70:47:57:A3:25:FD:82:D6:42:89:27:BA:
                            11:08:2B:95:02:21:00:D1:DD:7C:BE:0E:79:FC:D1:07:
                            67:5B:B4:DE:BD:D9:C2:6A:38:24:15:8F:A7:6A:C2:17:
                            03:C1:5B:25:75:C9:20
            Signed Certificate Timestamp:
                Version   : v1 (0x0)
                Log ID    : 13:4A:DF:1A:B5:98:42:09:78:0C:6F:EF:4C:7A:91:A4:
                            16:B7:23:49:CE:58:57:6A:DF:AE:DA:A7:C2:AB:E0:22
                Timestamp : Mar 28 19:19:22.914 2025 GMT
                Extensions: none
                Signature : ecdsa-with-SHA256
                            30:46:02:21:00:DD:71:4E:43:A8:D9:C6:0A:FF:05:E3:
                            6F:A4:B1:D9:ED:C8:5C:D7:31:03:7C:8E:5C:44:72:2B:
                            AE:84:5E:53:17:02:21:00:D0:D0:0F:5D:E8:7A:3A:DF:
                            02:60:5C:6D:02:47:83:E4:C5:74:79:66:B5:0A:58:DC:
                            61:AA:09:D2:88:90:9D:BA
Signature Algorithm: sha256WithRSAEncryption
Signature Value:
    32:43:12:cb:bb:7a:74:34:a6:f9:c6:8e:92:78:56:02:87:9f:
    02:03:f5:6b:be:b0:b9:e7:2b:21:6c:46:7d:27:20:91:00:64:
    5b:89:81:b7:de:13:e5:bc:a3:be:6b:30:c2:e5:e8:d0:82:74:
    c8:29:d1:29:10:df:29:a1:81:7e:9a:31:09:dc:fd:ef:6d:a8:
    93:e0:12:63:15:0f:fc:be:ad:33:32:49:bb:de:27:55:8a:2b:
    b9:a0:98:d9:ab:37:61:b6:ef:e0:81:fb:83:0f:de:30:0f:dc:
    bf:c0:62:54:90:d6:55:87:86:16:d3:2f:b4:6e:41:f7:d4:9e:
    4e:71:95:92:b3:7e:7e:50:35:11:94:b1:fe:6e:e5:b0:fc:8c:
    7c:28:c6:d2:40:03:8d:1a:17:c6:08:ee:84:95:7b:e8:ff:b3:
    ca:7d:37:e3:61:3d:ee:50:4b:7f:a6:90:81:db:fd:6e:8b:91:
    b7:c8:e9:1b:34:fc:57:8f:9a:3e:39:a1:72:6b:4a:13:19:72:
    88:62:90:f4:d7:b8:09:4e:56:d7:4b:30:bd:93:61:37:b8:9a:
    3e:3b:a4:7c:cc:ff:6e:1c:f2:9e:1d:54:78:90:d4:3f:93:0f:
    f4:cc:f6:3a:18:bd:1c:e0:d6:18:50:fe:55:68:b4:45:3e:12:
    2c:31:47:bb

Exercice 2 : Quantum-safe cryptography

In Quantum-safe cryptography – fundamentals, current developments and recommendations, the BSI (German Federal Office for Information Security) gives recommandations about the posture to adopt. Can you :

  • name the recommandations
  • state whether it is more important to adopt Quantum Key Distribution or Post Quantum Algorithms? Why?
  • explain whether the present PKI architecture (X.509, hierarchical structure, …) is ready for post-quantum cryptography
Solution

The responses are:

  • Post Quantum Algorithms are a priority as they are used throughout the infrastructure contrary to QKD. As per Mosca’s theorem, one would need to ensure that $ X + Y < Z $.
  • The solution is ready to accommodate new algorithms, so there is no need to modify the architecture from this standpoint.

Exercice 3 : Implement a securely communicating OPC UA Server

In a previous exercice, you have secured the communication to your OPC UA server. Should you have not, below you will find code snippets that will help you to do so.

Your task: based on the following scripts for generating the required certificates, modify them so that the certificates are signed by an intermediary CA and not a self-signed one (pretending to be root CA).

Certificate generation

  • generating the key for the OPC UA server

    #! /bin/bash
    
    openssl genrsa -out server_private.pem 2048
    
    openssl req -x509 -days 365 -new -out certificate.pem -key server_private.pem -config cert.conf
    openssl x509 -outform der -in certificate.pem -out certificate.der
    
    where cert.conf contains
    [ req ]
    default_bits = 2048
    default_md = sha256
    distinguished_name = subject
    req_extensions = req_ext
    x509_extensions = req_ext
    string_mask = utf8only
    prompt = no
    
    [ req_ext ]
    basicConstraints = CA:FALSE
    nsCertType = client, server
    keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment, keyCertSign
    extendedKeyUsage= serverAuth, clientAuth
    nsComment = "OpenSSL Generated Certificate"
    subjectKeyIdentifier=hash
    authorityKeyIdentifier=keyid,issuer
    subjectAltName = URI:urn:opcua:python:server,IP: 127.0.0.1
    
    
    [ subject ]
    countryName = CH
    stateOrProvinceName = ZH
    localityName = Zurich
    organizationName = Test
    commonName = PythonOpcUaServer
    

    Hint

    Adapt the information to make it yours 😉

  • generating the key for a client

    #! /bin/bash
    
    # Check if a name parameter is provided
    if [ -z "$1" ]; then
    echo "Usage: $0 <name>"
    exit 1
    fi
    
    # Use the provided name for the certificate and private key
    NAME=$1
    
    # Generate the private key
    openssl genrsa -out "${NAME}_private.pem" 2048
    openssl rsa -in "${NAME}_private.pem" -outform DER -out "${NAME}_private.der"
    
    # Generate the certificate
    openssl req -new -x509 -key "${NAME}_private.pem" -out "${NAME}_cert.pem" -days 365
    openssl x509 -outform der -in "${NAME}_cert.pem" -out "${NAME}_cert.der"
    
    echo "Certificate and private key generated:"
    echo "  Private Key: ${NAME}_private.key"
    echo "  Certificate: ${NAME}_cert.pem"
    

Server code

After namespace = server.register_namespace(Settings.service_name), add the following lines :

server.load_certificate("certificates/certificate.der")
server.load_private_key("certificates/server_private.pem")
server.set_security_policy([
                                #ua.SecurityPolicyType.NoSecurity,
                                #ua.SecurityPolicyType.Basic128Rsa15_Sign,
                                #ua.SecurityPolicyType.Basic128Rsa15_SignAndEncrypt,
                                #ua.SecurityPolicyType.Basic256Sha256_Sign,
                                ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt
                            ])

Warning

Depending what modes are activated, you will need to modify certificates and client code accordingly.

Bug

The GUI client (opcua-client) is currently not capable of connecting to the server and throws an error. Just use the command line alternative as the exercice is to have a secured channel established and, especially, have a PKI in place for handling the certificates.

Client code

from opcua import Client
import logging
from enviro import Settings

# Create a dedicated logger
logger = logging.getLogger('opcua_cont_client')
logger.setLevel(logging.INFO)

# Create console handler and set level to info
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)

# Create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Add formatter to ch
ch.setFormatter(formatter)

# Add ch to logger
logger.addHandler(ch)

# OPC UA Server Python
url = Settings.server_url 
client = Client(url)

if Settings.secure_communication:
    #client.set_user("user1")
    #client.set_password("pw1")
    client.set_security_string("Basic256Sha256,SignAndEncrypt,certificates/trusted_clients/client3_cert.der,certificates/trusted_clients/client3_private.pem")
    client.secure_channel_timeout = 100000
    client.session_timeout = 100000

try:
    client.connect()
    root = client.get_root_node()
    nodeId = root.get_child(["0:Objects", "2:Sensors", "2:Temperature"])
    logger.info("OPC UA Client Connected")
    logger.info(f"NodeId: {nodeId}")
    node = client.get_node(nodeId)
    value = node.get_value()
    logger.info(f"Value[°C]: {value}")

except Exception as e:
    logger.error(f"Connection failed: {e}")

finally:
    client.disconnect()

Warning

You will need to add secure_communication = True to Settings class (enviro.py).

Note

As you can see, the code contains

#client.set_user("user1")
#client.set_password("pw1")
In fact, the code would support user/password login - even though it is not recommended.

Solution

The solution requires to introduce an Intermediate CA that will be used to sign the certificates used by the clients/server. In order to do this:

  • remove the private key for signing the certificate
  • create a root CA
  • create an intermediate CA certificate
  • create a request for client/server certificate
  • use the intermediate CA private key to sign the requested certificate
  • install the root CA public certificate onto the machines needing the trust chains

Exercice 4 : Run Your Own PKI

Aim

In fact, in the previous exercice you embarked in an exciting adventure: you will become a Certificate Authority!!! Congratulations!!! 😎

After following the indications given in the previous exercice, where you a) created the CA private key and b) generated the root certificate, go about answering the following:

  1. What do the commands openssl genrsa -out server_private.pem 2048 and openssl req -x509 -days 365 -new -out certificate.pem -key server_private.pem -config cert.conf exactly?

  2. How would you install the root certificate under a) Windows 11, b) MacOS, c) Linux, d) Android and e) iOS?

  3. What would you need to pay especially attention to in case you were to run your own PKI?

    Solution
    1. The command openssl genrsa -des3 -out myCA.key 2048 and openssl req -x509 -new -nodes -key myCA.key -sha256 -days 1825 -out myCA.pem are used to generate a self-signed Certificate Authority (CA) certificate. Namely
    2. openssl genrsa -des3 -out myCA.key 2048, command that generates a private key for the CA.
      -des3 option specifying that the private key should be encrypted using the DES-EDE3-CBC (Triple DES) algorithm. This adds a layer of security by requiring a passphrase to access the private key. 2048 specifies the length of the RSA key in bits. A 2048-bit key is considered secure for most purposes.
    3. openssl req -x509 -new -nodes -key myCA.key -sha256 -days 1825 -out myCA.pem generates a self-signed X.509 certificate using the private key generated in the previous step.
      -x509 specifies that a self-signed certificate should be generated instead of a CSR -new indicates that a new certificate or CSR should be created -sha256 specifies that the SHA-256 hashing algorithm should be used for signing the certificate. SHA-256 is a secure hashing algorithm -days 1825 indicates the validity period of the certificate in days. In this case, the certificate will be valid for 1825 days (approximately 5 years).
    4. Installing a root certificate on different operating systems involves specific steps for each platform.

      • Windows
        • Download the Root Certificate to your computer
        • Open the Certificate Manager (certmgr.msc)
        • In the Certificate Manager, navigate to Trusted Root Certification Authorities > Certificates and then Import
      • MacOS
        • Download the Root Certificate to your computer
        • Open Keychain Access
        • Import the Certificate(File > Import Items)
        • Choose System as the keychain
        • Trust the Certificate - Find the imported certificate in the System keychain and duble-click the certificate to open its details. Expand the Trust section and set When using this certificate to Always Trust.
      • Linux
        • Download the Root Certificate to your computer
        • Copy the Certificate to the Trusted Directory (typically /usr/local/share/ca-certificates or /etc/ssl/certs)
        • Update the CA Certificates (e.g. sudo update-ca-certificates)
      • Android
        • Transfer the Certificate to the Device
        • Install the Certificate - Open the file manager or the app where you transferred the certificate, tap on the certificate file and follow the prompts to install the certificate
        • Verify the Installation by going to Settings > Security > Encryption & credentials > Trusted credentials and ensuring the certificate is listed under User or System credentials
      • iOS
        • Transfer the Certificate to the Device
        • Install the Certificate by tapping on the certificate file and follow the prompts to install the certificate. Do Trust the Certificate and check its presence under Settings > General > About > Certificate Trust Settings
    5. Running your own Public Key Infrastructure (PKI) involves several critical considerations to ensure security, reliability, and compliance. Here are some key areas to pay special attention to:

      • Security of the Root CA
        • Physical Security: The Root CA should be physically secured to prevent unauthorized access. This may involve storing the Root CA in a secure location, such as a locked room or a hardware security module (HSM)
        • Access Control: Implement strict access controls to ensure that only authorized personnel can access the Root CA Use multi-factor authentication (MFA) and role-based access control (RBAC)
        • Offline Storage: Consider keeping the Root CA offline (air-gapped) to minimize the risk of compromise. Bring it online only when necessary to issue intermediate certificates
      • Certificate Policies and Practices
        • Certificate Policy (CP): Define a clear certificate policy that outlines the rules and procedures for issuing, managing, and revoking certificates
        • Certificate Practice Statement (CPS): Develop a certificate practice statement that describes how the PKI is operated in accordance with the certificate policy
        • Validation Periods: Set appropriate validation periods for certificates to balance security and operational convenience
      • Key Management
        • Key Generation: Use strong, random key generation methods to ensure the security of the keys
        • Key Storage: Store private keys securely, using hardware security modules (HSMs) if possible
        • Key Rotation: Implement a key rotation policy to periodically replace keys and certificates to mitigate the risk of key compromise
      • Certificate Revocation
        • Certificate Revocation List (CRL): Maintain a CRL to list revoked certificates. Ensure that the CRL is regularly updated and distributed.
        • Online Certificate Status Protocol (OCSP): Implement OCSP to provide real-time certificate status information
        • Revocation Policies: Define clear policies for when and how certificates should be revoked, such as in cases of key compromise, employee termination, or policy violations
      • Compliance and Auditing
        • Regulatory Compliance: Ensure that your PKI complies with relevant regulations and industry standards, such as HIPAA, or GDPR
        • Audit Logs: Maintain detailed audit logs of all PKI activities, including certificate issuance, revocation, and access to the Root CA
        • Regular Audits: Conduct regular internal and external audits to ensure that the PKI is operating securely and in compliance with policies and regulations
      • Backup and Recovery
        • Backup: Regularly back up the Root CA, intermediate CAs, and all relevant keys and certificates
        • Recovery Plan: Develop a disaster recovery plan to ensure that the PKI can be restored in the event of a failure or compromise
        • Test Recovery: Periodically test the recovery plan to ensure that it is effective and up-to-date
      • Training and Awareness
        • Staff Training: Provide regular training to PKI administrators and users to ensure they understand the importance of security and the proper use of the PKI
        • User Awareness: Educate users about the risks associated with certificate misuse and the importance of reporting any suspicious activities
      • Monitoring and Alerts
        • Monitoring: Implement monitoring tools to continuously monitor the health and security of the PKI.
        • Alerts: Set up alerts to notify administrators of any unusual activities, such as unauthorized access attempts or certificate revocations
      • Intermediate CAs
        • Hierarchical Structure: Use intermediate CAs to issue end-entity certificates, reducing the risk of compromise to the Root CA
        • Segregation of Duties: Assign different roles and responsibilities for managing the Root CA and intermediate CAs to minimize the risk of insider threats
      • Documentation
        • Documentation: Maintain comprehensive documentation of the PKI architecture, policies, procedures, and configurations
        • Updates: Regularly update the documentation to reflect any changes in the PKI or its policies
      • Automation and Integration
        • Automation: Automate repetitive tasks, such as certificate issuance and revocation, to reduce the risk of human error
        • Integration: Integrate the PKI with other systems, such as identity management systems, to streamline certificate management

      By paying special attention to these areas, you can ensure that your PKI is secure, reliable, and compliant, providing a strong foundation for secure communication and authentication within your organization. If you do not similiraties with the NIST Cybersecurity Framework, well, it is no coincidence 😉