Certificate Generation and Configuration
- For an overview of Safe Mode / Token, please see Security Encryption.
- How to pass parameters when creating a Session—see PFX Constructor.
Generate Client PFX
Use OpenSSL CLI (Recommended)
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:
| Server | Path |
|---|---|
| Darra Software PLC Server | %ProgramData%\Darra\PKI\trusted\certs (Restart the service after copying for the changes to take effect) |
| The customer's current server | Imported 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:
| Configuration | Default value |
|---|---|
trust_list_dir | %ProgramData%\Darra\PKI\trusted\certs |
rejected_dir | %ProgramData%\Darra\PKI\rejected\certs |
auto_accept_untrusted | false — 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 retrievedget_endpointsfrom [EndpointDescription.server_certificatesource].None TOFU / Fingerprint storage and comparison, Not passing it means the server's identity is not verified. - Explicit Passing
server_cert_pathPoint 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:- No DER. It only supports the PKCS#12 format; attempting to load a file with a slash (
.der/) will inevitably.pemfail. - No password is allowed. — Server certificates: Passwords are PFX not accepted; those with passwords cannot be PFX decrypted.
- 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 failedline in the logs.
- No DER. It only supports the PKCS#12 format; attempting to load a file with a slash (
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).
| StatusCode | Reason | Resolve |
|---|---|---|
| BadCertificateUntrusted | The server does not trust the client. | Copy client.der to the server's trusted/certs/ directory. |
| BadCertificateInvalid | Certificate has expired / is not yet valid | Regenerate |
| BadCertificateTimeInvalid | The machine time is outside the certificate's validity period. | Synchronize the time (see "Time Synchronization"); if that doesn't work, regenerate it. |
| BadCertificateUriInvalid | The 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 ) |
| BadCertificateHostNameInvalid | The SAN.DNS certificate does not match the connected host. | When generating, add subjectAltName=DNS:server.example.com |
| BadSecurityChecksFailed | General security validation failed | Check the server logs to determine the specific cause. |
| BadSecurityModeRejected | The server does not support this SecurityMode | get_endpoints Check which ones the server actually supports |
| BadSecurityPolicyRejected | The 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