Skip to main content

Certificate Generation and Configuration

Prerequisite Reading

Generate Client PFX​

openssl req -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes \
-subj "/CN=MyClient/O=Darra/C=CN" \
-addext "subjectAltName=URI:urn:darra:opcua:client"

openssl pkcs12 -export -out client.pfx -inkey key.pem -in cert.pem -password pass:123456

# Also export the DER public key for use in the server's trusted/ directory.
openssl x509 -in cert.pem -outform der -out client.der

Using Python packages cryptography​

from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import pkcs12
import datetime as dt

key = rsa.generate_private_key(public_exponent=65537, key_size=2048)

subject = issuer = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, "MyClient"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "My Company"),
x509.NameAttribute(NameOID.COUNTRY_NAME, "CN"),
])

cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(dt.datetime.utcnow())
.not_valid_after(dt.datetime.utcnow() + dt.timedelta(days=365))
.add_extension(
x509.SubjectAlternativeName([
x509.UniformResourceIdentifier("urn:darra:opcua:client"),
]),
critical=False)
.sign(key, hashes.SHA256())
)

pfx_bytes = pkcs12.serialize_key_and_certificates(
name=b"MyClient",
key=key,
cert=cert,
cas=None,
encryption_algorithm=serialization.BestAvailableEncryption(b"123456"))

with open(r"C:\certs\client.pfx", "wb") as f:
f.write(pfx_bytes)

# DER Public Key (server: trusted/)
with open(r"C:\certs\client.der", "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.DER))

Importing Trust on the Server Side​

Copy the client's public key (.der or .pem) to the server's "Trusted Client Certificates" directory:

ServerPath
Darra Software PLC Server%ProgramData%\Darra\PKI\trusted\certs (Restart the service after copying for the changes to take effect)
The customer's current serverImported by the remote operations team; the path is in the format <server>/pki/trusted/certs/ or uploaded to the management console.

Darra Software PLC Server Default values related to the trust directory:

ConfigurationDefault value
trust_list_dir%ProgramData%\Darra\PKI\trusted\certs
rejected_dir%ProgramData%\Darra\PKI\rejected\certs
auto_accept_untrustedfalse — Untrusted client certificateNo If it is automatically accepted, it will end up in rejected\certs

Therefore, when the client certificate is not imported, the following occurs: the connection is rejected (BadCertificateUntrusted), and the certificate is placed in rejected\certs instead of being automatically trusted.

Passed when the client is constructed PFX​

client_key_path The rumor is thatThe password PFX for that, This is not the path to the private key file (PFX the private key is already included); if there is no password, just PFX leave it blank.security_mode SignAndEncrypt When signing, if you do not specify a password, the system will automatically security_policy_uri use the default one #Basic256Sha256.

from darra_opcua import OpcUaSession, MessageSecurityMode

with OpcUaSession(
endpoint_url="opc.tcp://server:4840",
security_mode=MessageSecurityMode.SignAndEncrypt,
client_cert_path=r"C:\certs\client.pfx",
client_key_path="123456", # PFX Password
server_cert_path=None) as ua: # Do not pass the server certificate; use None→Secure for automatic upgrade
ua.connect()

How do I provide the server certificate?​

  • Not to be disclosed server_cert_path: Switch from None to Secure via automatic upgrade — the server certificate is retrieved get_endpoints from [ EndpointDescription.server_certificate source].None TOFU / Fingerprint storage and comparison, Not passing it means the server's identity is not verified.
  • Explicit Passingserver_cert_path Point to the server certificate PFX (PKCS#12) File — This is the only option, suitable for production environments where server certificates remain fixed. Three pitfalls you must be aware of:
    1. No DER. It only supports the PKCS#12 format; attempting to load a file with a slash ( .der /) will inevitably .pem fail.
    2. No password is allowed. — Server certificates: Passwords are PFX not accepted; those with passwords cannot be PFX decrypted.
    3. Loading failed with no error message: just log a single WARN and fall back to the auto-discovery above; the connection still succeeds. It looks like you pinned the server's identity, but you did not. The SDK also has no API to query whether the server certificate loaded — you can only confirm it from the Server cert PFX load failed line in the logs.
server_cert_path=r"C:\certs\server.pfx"   # Server Certificate PFX (PKCS#12), Passwordless

Troubleshooting​

The names in the table below are the OPC UA status codes the server can return, read from OpcUaException.status_code. The StatusCode enumeration only covers common codes; codes not listed (such as BadCertificateUntrusted / BadCertificateUriInvalid / BadCertificateHostNameInvalid) appear as raw integers in e.status_code and should be cross-checked against the server log with hex(e.status_code).

StatusCodeReasonResolve
BadCertificateUntrustedThe server does not trust the client.Copy client.der to the server's trusted/certs/ directory.
BadCertificateInvalidCertificate has expired / is not yet validRegenerate
BadCertificateTimeInvalidThe machine time is outside the certificate's validity period.Synchronize the time (see "Time Synchronization"); if that doesn't work, regenerate it.
BadCertificateUriInvalidThe certificate does not ApplicationUri match the one reported by SAN.URI the client.SAN URI Written as urn:darra:opcua:client (see “Importance”SAN URI )
BadCertificateHostNameInvalidThe SAN.DNS certificate does not match the connected host.When generating, add subjectAltName=DNS:server.example.com
BadSecurityChecksFailedGeneral security validation failedCheck the server logs to determine the specific cause.
BadSecurityModeRejectedThe server does not support this SecurityModeget_endpoints Check which ones the server actually supports
BadSecurityPolicyRejectedThe server does not support Basic256Sha256.Enable this policy in the server configuration

SAN URI Importance​

The data reported by the client ApplicationUri isFixed Value urn:darra:opcua:client, The value SAN in the certificate must URI: be entered exactly as shown, without any discrepancies. If it does not match the server's record, the request will be rejected with the error "Client identity does not match the certificate" (BadCertificateUriInvalid / BadSecurityChecksFailed). The Python constructor does not have a parameter to modify this value; simply generate it using the two examples above. OpenSSL Verify using:

openssl pkcs12 -in client.pfx -password pass:123456 -nokeys -out client.pem
openssl x509 -in client.pem -text -noout | grep -A1 "Subject Alternative Name"

Or Python:

from cryptography import x509
from cryptography.hazmat.primitives.serialization import pkcs12

with open(r"C:\certs\client.pfx", "rb") as f:
_, cert, _ = pkcs12.load_key_and_certificates(f.read(), b"123456")

san = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
uris = [u.value for u in san.get_values_for_type(x509.UniformResourceIdentifier)]
print(f"SAN URIs: {uris}")

if "urn:darra:opcua:client" not in uris:
print("ERROR: 证书 SAN URI 缺 urn:darra:opcua:client, 重新生成!")

Time Synchronization (NTP)​

Certificates have a fixed validity period (notValidBefore / notValidAfter), and the server processes them according toIts own clock Validation. Incorrect system time → The server rejects the connection and returns BadCertificateTimeInvalid / BadCertificateInvalid. In a production environment NTP, clock deviation must be kept within seconds.

w32tm /resync

Next Step​