인증서 생성 및 구성
클라이언트 생성 PFX
사용 OpenSSL CLI (추천)
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
# 동시에 공개 키를 DER 내보내어, 서버 측 trusted/에 사용합니다.
openssl x509 -in cert.pem -outform der -out client.der
Python 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 공개 키 (서버 측 trusted/)
with open(r"C:\certs\client.der", "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.DER))
서버 측 신뢰 설정
클라이언트 공개 키(.der 또는 .pem)를 서버의 "신뢰할 수 있는 클라이언트 인증서" 디렉터리에 복사합니다:
| Server | 경로 |
|---|---|
| Darra Software PLC Server | %ProgramData%\Darra\PKI\trusted\certs (복사한 후 서비스를 다시 시작해야 적용됩니다) |
| 고객의 기존 서버 | 상대 측 운영팀에서 가져오기를 담당하며, 경로는 <server>/pki/trusted/certs/와 같은 형식이어야 하거나 관리자 콘솔에 업로드해야 합니다. |
Darra Software PLC Server 신뢰 디렉터리와 관련된 기본값:
| 구성 | 기본값 |
|---|---|
trust_list_dir | %ProgramData%\Darra\PKI\trusted\certs |
rejected_dir | %ProgramData%\Darra\PKI\rejected\certs |
auto_accept_untrusted | false — 인증되지 않은 클라이언트 인증서아니요자동으로 수락되면, 다음으로 이동하게 됩니다 rejected\certs |
따라서 클라이언트 인증서가 가져오지 않은 경우 나타나는 현상은 다음과 같습니다: 연결이 거부되고 (BadCertificateUntrusted), 인증서가 자동으로 신뢰되지 rejected\certs 않고 로 이동합니다.
클라이언트 생성 시 전달 PFX
client_key_path 전해지는 바에 따르면해당 비밀번호 PFX, 개인 키 파일 경로가 아닙니다 (PFX 이미 개인 키가 포함되어 있음); 비밀번호가 없는 경우 PFX 빈칸으로 두시면 됩니다.security_mode Sign / SignAndEncrypt 시, 전달하지 않으면 자동으로 security_policy_uri 사용됩니다 #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 비밀번호
server_cert_path=None) as ua: # 서버 인증서를 전달하지 않고, None→Secure 경로를 통해 자동 업그레이드
ua.connect()
서버 인증서는 어떻게 발급하나요?
- 비공개
server_cert_path: None→Secure로 자동 업그레이드 — 서버 인증서는get_endpoints에서 받은EndpointDescription.server_certificate을 사용합니다.전혀 없음 TOFU / 지문 보존 및 대조, 전달하지 않는 것은 서버의 신원을 확인하지 않는 것과 같습니다. - 명시적 전달
server_cert_path서버 인증서 지정 PFX (PKCS#12) 파일 —— 이 방법만 인정하며, 서버 인증서가 고정된 프로덕션 환경에 적합합니다. 반드시 알아야 할 세 가지 주의사항:- 아니다 DER. PKCS#12 형식만 지원하며,
.der/를 전달하면 반드시 로딩에.pem실패합니다. - 반드시 비밀번호가 없어야 합니다 —— 서버 인증서는 PFX 비밀번호를 허용하지 않으며, 비밀번호가 설정된 경우 PFX 해독할 수 없습니다.
- 로딩 실패 시 오류 메시지가 표시되지 않음: WARN 메시지가 하나만 출력된 후 위의 자동 탐색 단계로 돌아가면, 연결은 여전히 성공합니다.마치 서버의 신원을 고정했다고 생각하지만, 실제로는 고정되지 않은 것과 같다.SDK 또한 "서버 측 인증서가 성공적으로 로드되었는지"를 확인할 수 있는 조회 인터페이스도 없어, 로그를 통해서만
Server cert PFX load failed확인할 수 있습니다.
- 아니다 DER. PKCS#12 형식만 지원하며,
server_cert_path=r"C:\certs\server.pfx" # 서버 인증서 PFX (PKCS#12), 비밀번호 없음
문제 해결
아래 표의 코드명은 서버에서 반환하는 상태 OPC UA 코드이며, 에서 OpcUaException.status_code 읽을 수 있습니다.SDK 의 StatusCode 열거형에는 자주 사용되는 코드만 포함되어 있으며, 포함되지 않은 코드(예: BadCertificateUntrusted / BadCertificateUriInvalid / BadCertificateHostNameInvalid)는 원시 int 형식으로 에 나타나므로 e.status_code, hex(e.status_code) 와 서버 로그를 대조하여 확인하십시오.
| StatusCode | 이유 | 해결 |
|---|---|---|
| BadCertificateUntrusted | 서버가 클라이언트를 신뢰하지 않음 | client.der 를 서버의 trusted/certs/ 디렉터리에 복사합니다. |
| BadCertificateInvalid | 인증서 만료 / 유효하지 않음 | 다시 생성 |
| BadCertificateTimeInvalid | 머신 시간이 인증서 유효 기간 내에 있지 않습니다. | 시간 동기화(「시간 동기화」 참조), 그래도 안 되면 다시 생성 |
| BadCertificateUriInvalid | 인증서가 클라이언트가 SAN.URI 보고한 내용과 일치하지 ApplicationUri 않습니다. | SAN URI ~로 작성 ( urn:darra:opcua:client 「SAN URI 중요성」 참조) |
| BadCertificateHostNameInvalid | 인증서가 연결된 호스트와 SAN.DNS 일치하지 않습니다. | 생성 시 subjectAltName=DNS:server.example.com을 추가합니다. |
| BadSecurityChecksFailed | 일반 보안 검증 실패 | 서버 로그를 확인하여 구체적인 원인을 파악하십시오. |
| BadSecurityModeRejected | 서버 측에서는 이를 지원하지 않습니다. SecurityMode | get_endpoints 서버 측에서 실제로 어떤 기능을 지원하는지 확인해 보세요 |
| BadSecurityPolicyRejected | 서버 측에서 Basic256Sha256을 지원하지 않습니다. | 서버 측 구성에서 해당 정책을 활성화합니다. |
SAN URI 중요성
클라이언트가 보고한 ApplicationUri 내용은고정값 urn:darra:opcua:client, 인증서 SAN 내의 URI: 값은 한 글자도 틀리지 않고 정확히 동일하게 입력해야 합니다. 일치하지 않을 경우 서버 측에서 "클라이언트 신원과 인증서가 일치하지 않음"을 이유로 거부합니다 (BadCertificateUriInvalid / BadSecurityChecksFailed). Python 생성자에는 이 값을 변경하는 매개변수가 없으므로, 위의 두 예시와 같이 생성하면 됩니다. 다음을 사용하여 OpenSSL 확인합니다:
openssl pkcs12 -in client.pfx -password pass:123456 -nokeys -out client.pem
openssl x509 -in client.pem -text -noout | grep -A1 "Subject Alternative Name"
또는 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, 重新生成!")
시간 동기화 (NTP)
인증서에는 고정된 유효 기간(notValidBefore / notValidAfter)이 있으며, 서버는자체 시계검증. 시스템 시간이 맞지 않음 → 서버가 연결을 거부하고 BadCertificateTimeInvalid / 오류를 반환함 BadCertificateInvalid NTP. 운영 환경에서는 시계 오차를 초 단위로 제어해야 합니다.
w32tm /resync