OPC UA Secure Conversation (UASC) allows secure communication using binary encoded Messages.

UASC is designed to operate with different TransportProtocolsthat may have limited buffer sizes. For this reason, OPC UA Secure Conversation will break OPC UA Messagesinto several pieces (called ‘MessageChunks’) that are smaller than the buffer size allowed by the TransportProtocol. UASC requires a TransportProtocol buffer size that is at least 8 192 bytes when using RSA based Asymmetric CryptographyThis minimum buffer size drops to 1 024 when using ECC based Asymmetric Cryptography (see 6.8) is supported.

All security is applied to individual MessageChunksand not the entire OPC UA Message. A Stackthat implements UASC is responsible for verifying the security on each MessageChunkreceived and reconstructing the original OPC UA Message.

All MessageChunkswill have a 4-byte sequence assigned to them. These sequence numbers are used to detect and prevent replay attacks.

UASC requires a TransportProtocolthat will preserve the order of MessageChunks, however, a UASC implementation does not necessarily process the Messagesin the order that they were received.

The structure of the Messagedepends on whether the SecurityPolicyrequires an algorithm that combines encryption and authentication (e.g. Authenticated Encryptionalgorithms) used or if it requires separate algorithms for each operation (Unauthenticated Encryption algorithms).

Figure 11shows the structure of a MessageChunkand how security is applied to the Messagewhen using Unauthenticated Encryptionalgorithms. For these SecurityPoliciesany padding is appended to the message before appending the Signature.

image014.png

Figure 11– MessageChunk for Unauthenticated Encryption Algorithms

Figure 12shows the structure of a MessageChunkand how security is applied to the Messagewhen using Authenticated Encryptionalgorithms. For these SecurityPoliciesthe Signatureis calculated during encryption and appended after the encrypted data. Paddingis not needed.

image015.png

Figure 12– MessageChunk for Authenticated Encryption Algorithms

Every MessageChunkhas a Messageheader with the fields defined in Table 50.

Table 50– OPC UA Secure ConversationMessage Header

Name

Data Type

Description

MessageType

Byte [3]

A three byte ASCII code that identifies the Messagetype.

The following values are defined at this time:

MSGA Messagesecured with the keys associated with a channel.

OPN OpenSecureChannel Message.

CLO CloseSecureChannel Message.

IsFinal

Byte

A one byte ASCII code that indicates whether the MessageChunkis the final chunk in a Message.

The following values are defined at this time:

C An intermediate chunk.

F The final chunk.

A The final chunk (used when an error occurred and the Messageis aborted).

This field is only meaningful for MessageType of ‘MSG’

This field is always ‘F’ for other MessageTypes.

MessageSize

UInt32

The length of the MessageChunk, in bytes.

The length starts from the beginning of the MessageType field.

SecureChannelId

UInt32

A unique identifier for the SecureChannelassigned by the Server.

If a Serverreceives a SecureChannelId which it does not recognize it shall return an appropriate transport layer error.

When a Serverstarts the first SecureChannelIdused should be a value that is likely to be unique after each restart. This ensures that a Serverrestart does not cause previously connected Clientsto accidently ‘reuse’ SecureChannelsthat did not belong to them.

The Messageheader is followed by a security header which specifies what cryptography operations have been applied to the Message. There are two versions of the security header which depend on the type of security applied to the Message. The security header used for asymmetric algorithms is defined in Table 51. Asymmetric algorithms are used to secure the OpenSecureChannel Messages. PKCS #1defines a set of asymmetric algorithms that may be used by UASC implementations. The AsymmetricKeyWrapAlgorithmelement of the SecurityPolicystructure defined in Table 42is not used by UASC implementations.

Table 51– Asymmetric algorithm Security header

Name

Data Type

Description

SecurityPolicyUriLength

Int32

The length of the SecurityPolicyUriin bytes.

This value shall not exceed 255 bytes.

If a URI is not specified this value may be 0 or -1.

Other negative values are invalid.

SecurityPolicyUri

Byte []

The URI of the Security Policyused to secure the Message.

This field is encoded as a UTF-8string without a null terminator.

SenderCertificateLength

Int32

The length of the SenderCertificatein bytes.

This value shall not exceed MaxSenderCertificateSizebytes.

If a certificate is not specified this value may be 0 or -1.

Other negative values are invalid.

SenderCertificate

Byte []

The X.509 v3 Certificateassigned to the sending applicationInstance.

This is a DER encoded blob.

The structure of an X.509 v3 Certificateis defined in X.509 v3.

The DER format for a Certificateis defined in X690

This indicates what Private Keywas used to sign the MessageChunk.

The Stackshall close the channel and report an error to the application if the SenderCertificateis too large for the buffer size supported by the transport layer.

This field shall be null if the Messageis not signed.

If the Certificateis signed by a CA, the DER encoded CA Certificatemay be appended after the Certificate in the byte array. If the CA Certificateis also signed by another CA this process is repeated until the entire Certificate chain is in the buffer or if MaxSenderCertificateSizelimit is reached (the process stops after the last whole Certificatethat can be added without exceeding the MaxSenderCertificateSizelimit).

Receivers can extract the Certificatesfrom the byte array by using the Certificatesize contained in DER header (see X.509 v3).

Receivers that do not handle Certificatechains shall ignore the extra bytes.

ReceiverCertificateThumbprintLength

Int32

The length of the ReceiverCertificateThumbprintin bytes.

If encrypted, the value of this field is 20 bytes.

If not encrypted the value may be 0 or -1.

Other negative values are invalid.

ReceiverCertificateThumbprint

Byte []

The thumbprint of the X.509 v3 Certificateassigned to the receiving applicationInstance.

The thumbprint is the CertificateDigestof the DER encoded form of the Certificate.

This indicates what public key was used to encrypt the MessageChunk.

This field shall be null if the Messageis not encrypted.

The receiver shall close the communication channel if any of the fields in the security header have invalid lengths.

The SenderCertificate, includingany chains,shall be small enough to fit into a single MessageChunkand leave room for at least one byte of body information. The maximum size for the SenderCertificatecan be calculated with this formula:

MaxSenderCertificateSize =

MessageChunkSize –

12 - // Header size

4 - // SecurityPolicyUriLength

SecurityPolicyUri -// UTF-8 encoded string

4 - // SenderCertificateLength

4 - // ReceiverCertificateThumbprintLength

20 - // ReceiverCertificateThumbprint

8 - // SequenceHeader size

1 - // Minimum body size

1 - // PaddingSize if present

Padding - // Padding if present

ExtraPadding - // ExtraPadding if present

AsymmetricSignatureSize// If present

The MessageChunkSizedepends on the transport protocol but shall be at least 8 192 bytes. The AsymmetricSignatureSizedepends on the number of bits in the public key for the SenderCertificate. The Int32FieldLengthis the length of an encoded Int32 value and it is always 4 bytes.

The security header used for symmetric algorithms defined in Table 52. Symmetric algorithms are used to secure all Messagesother than the OpenSecureChannel Messages. FIPS 197define symmetric encryption algorithms that UASC implementations may use. FIPS 180-and HMACdefine some symmetric signature algorithms.

Table 52– Symmetric algorithm Security header

Name

Data Type

Description

TokenId

UInt32

A unique identifier for the SecureChannel SecurityTokenused to secure the Message.

This identifier is returned by the Serverin an OpenSecureChannelresponse Message. If a Serverreceives a TokenId which it does not recognize it shall return an appropriate transport layer error.

The security header is always followed by the sequence header which is defined in Table 53. The sequence header ensures that the first encrypted block of every Messagesent over a channel will start with different data.

Table 53– Sequence header

Name

Data Type

Description

SequenceNumber

UInt32

A monotonically increasing sequence number assigned by the sender to each MessageChunksent over the SecureChannel.

RequestId

UInt32

An identifier assigned by the Clientto OPC UA request Message. All MessageChunksfor the request and the associated response use the same identifier.

ASequenceNumber may not be reused for any TokenId. The SecurityTokenlifetime shall be short enough to ensure that this never happens; however, if it does the receiver shall treat it as a transport error and force a reconnect. The SequenceNumber does not reset when a new TokenId is issued and it shall be incremented by exactly one for each MessageChunk sent.

SecurityPolicies with LegacySequenceNumbersset to TRUE, the SequenceNumber shall monotonically increase for all Messages and shall not wrap around until it is greater than 4 294 966 271 (UInt32.MaxValue – 1 024). The first number after the wrap around shall be less than 1 024.

SecurityPolicies with LegacySequenceNumbersset to FALSE, the SequenceNumber shall start at 0 and monotonically increase for all Messages and shall not wrap around until it is equal to 4 294 967 295 (UInt32.MaxValue). The first number after the wrap around shall be 0.

Some applications will find it takes time to validate the OpenSecureChannel Requestsand Responsesused to renew a TokenId. In these situations, the receiver may assume the SequenceNumberis correct which allows it to process subsequent messages secured with the existing TokenIdbefore the OpenSecureChannel Messageis validated. When processing of the OpenSecureChannel Message completes, the receiver checks the SequenceNumberand closes the SecureChannelif it is incorrect.

The sequence header is followed by the Messagebody which is encoded with the OPC UA Binary encoding as described in 5.2.9. The body may be split across multiple MessageChunks.

Each MessageChunkwhen using SecurityPolicieswith an Unauthenticated Encryptionalgorithms have a footer with the fields defined in Table 54.

Table 54Message Footer for Unauthenticated Encryption Algorithms

Name

Data Type

Description

PaddingSize

Byte

The number of padding bytes (not including the byte for the PaddingSize).

Padding

OctetString

Padding added to the end of the Messageto ensure length of the data to encrypt is an integer multiple of the encryption block size.

The value of each byte of the padding is equal to PaddingSize.

ExtraPaddingSize

Byte

The most significant byte of a two-byte integer used to specify the padding size when the key used to encrypt the message chunk is larger than 2 048 bits. This field is omitted if the key length is less than or equal to 2 048 bits.

Signature

OctetString

The signature for the MessageChunk.

The signature includes the headers, all Messagedata, the PaddingSizeand the Padding.

The signature is encoded as sequence of Bytes with a length specified by theSecurityPolicy.

The formula to calculate the amount of padding depends on the amount of data that needs to be sent (called BytesToWrite). The sender shall first calculate the maximum amount of space available in the MessageChunk(called MaxBodySize) using the following formula:

MaxBodySize = PlainTextBlockSize * Floor ((MessageChunkSize – MessageHeaderSize - SecurityHeaderSize – SignatureSize - 1)/CipherTextBlockSize) – SequenceHeaderSize;

The MessageHeaderSizeis 12 bytes and the SecurityHeadersize depends on whether symmetric or asymmetric cryptography is used. The SequenceHeaderSizeis always 8 bytes.

During encryption a block with a size equal to PlainTextBlockSizeis processed to produce a block with size equal to CipherTextBlockSize. These values depend on the encryption algorithm and may be the same.

The OPC UA Messagecan fit into a single chunk if BytesToWriteis less than or equal to the MaxBodySize. In this case the PaddingSizeis calculated with this formula:

PaddingSize = PlainTextBlockSize –

((BytesToWrite + SignatureSize + 1) % PlainTextBlockSize);

If the BytesToWriteis greater than MaxBodySizethe sender shall write MaxBodySizebytes with a PaddingSize of 0. The remaining BytesToWriteMaxBodySizebytes shall be sent in subsequent MessageChunks.

The PaddingSizeand Paddingfields are not present if the MessageChunkis not encrypted.

The Signature field is not present if the MessageChunk is not signed.

Each MessageChunkwhen using SecurityPolicieswith an Authenticated Encryptionalgorithms have a footer with the fields defined in Table 55.

Table 55Message Footer for Authenticated Encryption Algorithms

Name

Data Type

Description

Signature

OctetString

The signature for the MessageChunk.

The signature includes the headers and all Messagedata.

The signature is encoded as sequence of Bytes with a length specified by theSecurityPolicy.

MessageChunksare sent as they are encoded. MessageChunksbelonging to the same Messageshall be sent sequentially. If an error occurs creating a MessageChunk then the sender shall send a final MessageChunk to the receiver that tells the receiver that an error occurred and that it should discard the previous chunks. The sender indicates that the MessageChunk contains an error by setting the IsFinal flag to ‘A’ (for Abort). Table 56specifies the contents of the Messageabort MessageChunk.

Table 56– OPC UA Secure ConversationMessage abort body

Name

Data Type

Description

Error

UInt32

The numeric code for the error.

Possible values are listed in Table 70.

Reason

String

A more verbose description of the error.

This string shall not be more than 4 096 bytes.

A Clientshall ignore strings that are longer than this.

The receiver shall check the security on the abort MessageChunk before processing it. If everything is ok, then the receiver shall ignore the Messagebut shall not close the SecureChannel. The Clientshall report the error back to the application as StatusCodefor the request. If the Clientis the sender, then it shall report the error without waiting for a response from the Server.

Most Messagesrequire a SecureChannelto be established. A Clientdoes this by sending an OpenSecureChannelrequest to the Server. The Servershall validate the Messageand the ClientCertificateand return an OpenSecureChannelresponse. Some of the parameters defined for the OpenSecureChannelservice are specified in the security header (see 6.7.2) instead of the body of the Message. Table 57lists the parameters that appear in the body of the Message.

Note that OPC 10000-4is an abstract specification which defines interfaces that can work with any protocol. This document provides a concrete implementation for specific protocols. This document is the normative reference for all protocols and takes precedence if there are differences with OPC 10000-4.

Table 57– OPC UA Secure Conversation OpenSecureChannel Service

Name

Data Type

Request

RequestHeader

RequestHeader

ClientProtocolVersion

UInt32

RequestType

SecurityTokenRequestType

SecurityMode

MessageSecurityMode

ClientNonce

ByteString

RequestedLifetime

UInt32

Response

ResponseHeader

ResponseHeader

ServerProtocolVersion

UInt32

SecurityToken

ChannelSecurityToken

SecureChannelId

UInt32

TokenId

UInt32

CreatedAt

UtcTime

RevisedLifetime

UInt32

ServerNonce

ByteString

The ClientProtocolVersionand ServerProtocolVersionparameters are not defined in OPC 10000-4and are added to the Messageto allow backward compatibility if OPC UA-SecureConversation needs to be updated in the future.

If OPC UA-SecureConversationis used with the OPC UA-TCP protocol (see 7.1) then the ClientProtocolVersionspecified in the OpenSecureChannel Requestshall be the same as the ProtocolVersionspecified in the Hello Message. In addition, the ServerProtocolVersionspecified in the OpenSecureChannel Responseshall be the same as the ProtocolVersionspecified in the Acknowledge Message. The receiver shall close the channel and report a Bad_ProtocolVersionUnsupportederror if there is a mismatch.

The Servershall return an error response as described in OPC 10000-4if there are any errors with the parameters specified by the Client.

The RevisedLifetimetells the Clientwhen it shall renew the SecurityTokenby sending another OpenSecureChannelrequest. The Clientshall continue to accept the old SecurityTokenuntil it receives the OpenSecureChannelresponse. The Servershall accept requests secured with the old SecurityTokenuntil that SecurityTokenexpires or until it receives a Messagefrom the Clientsecured with the new SecurityToken. The Servershall reject renew requests if the SenderCertificateis not the same as the one used to create the SecureChannelor if there is a problem decrypting or verifying the signature. The Clientshall abandon the SecureChannelif the Certificateused to sign the response is not the same as the Certificateused to encrypt the request. Note that datatype is a UInt32value representing the number of milliseconds instead of the Double(Duration) defined in OPC 10000-4. This optimization is possible because sub-millisecond timeouts are not supported.

The OpenSecureChannel Messagesare signed and encrypted if the SecurityModeis not None(even if the SecurityMode is Sign).

The Noncesshall be cryptographic random numbers with a length specified by the SecureChannelNonceLength of the SecurityPolicy.

See OPC 10000-2for more information on the requirements for random number generators. The OpenSecureChannel Messagesare not signed or encrypted if the SecurityModeis None. The Noncesare ignored and should be set to null. The SecureChannelIdand the TokenIdare still assigned but no security is applied to Messagesexchanged via the channel. The SecurityTokenshall still be renewed before the RevisedLifetimeexpires. Receivers shall still ignore invalid or expired TokenIds.

The AuthenticationTokenin the RequestHeadershall be set to null.

If an error occurs after the Serverhas verified Messagesecurity it shall return a ServiceFaultinstead of a OpenSecureChannelresponse. The ServiceFault Messageis described in OPC 10000-4.

If the SecurityModeis not None then the Servershall verify that a SenderCertificateand a ReceiverCertificateThumbprintwere specified in the SecurityHeader.

Once the SecureChannelis established the Messagesare signed and encrypted with keys derived from the Noncesexchanged in the OpenSecureChannelcall. These keys are derived by passing the Noncesto a pseudo-random function (PRF) which produces a sequence of bytes from a set of inputs. A pseudo-random function is represented by the following function declaration:

Byte[] PRF(

Byte[] secret,

Byte[] seed,

Int32 length,

Int32 offset)

Where lengthis the number of bytes to return and offsetis a number of bytes from the beginning of the sequence.

The lengths of the keys that need to be generated depend on the SecurityPolicyused for the channel. The following information is specified by the SecurityPolicy:

  1. SigningKeyLength(from the DerivedSignatureKeyLength);
  2. EncryptingKeyLength(implied by the SymmetricEncryptionAlgorithm);
  3. IntializationVectorLength(from by the IntializationVectorLength).

The pseudo random function requires a secret and a seed. These values are derived from the Noncesexchanged in the OpenSecureChannelrequest and response. Table 58specifies how to derive the secrets and seeds when using RSA based SecurityPolicies.

Table 58– PRF inputs for RSA based SecurityPolicies

Name

Derivation

ClientSecret

The value of the ClientNonceprovided in the OpenSecureChannelrequest.

ClientSeed

The value of the ClientNonceprovided in the OpenSecureChannelrequest.

ServerSecret

The value of the ServerNonceprovided in the OpenSecureChannelresponse.

ServerSeed

The value of the ServerNonceprovided in the OpenSecureChannelresponse.

The parameters passed to the pseudo random function are specified in Table 59.

Table 59– Cryptography key generation parameters

Key

Secret

Seed

Length

Offset

ClientSigningKey

ServerSecret

ClientSeed

SigningKeyLength

0

ClientEncryptingKey

ServerSecret

ClientSeed

EncryptingKeyLength

SigningKeyLength

ClientInitializationVector

ServerSecret

ClientSeed

IntializationVectorLength

SigningKeyLength+EncryptingKeyLength

ServerSigningKey

ClientSecret

ServerSeed

SigningKeyLength

0

ServerEncryptingKey

ClientSecret

ServerSeed

EncryptingKeyLength

SigningKeyLength

ServerInitializationVector

ClientSecret

ServerSeed

IntializationVectorLength

SigningKeyLength+EncryptingKeyLength

The Clientkeys are used to secure Messagessent by the Client. The Serverkeys are used to secure Messagessent by the Server.

The SSL/TLSspecification defines a pseudo random function called P_HASH which is used for this purpose. The function is iterated until it produces enough data for all of the required keys. The Offset in Table 59references to the offset from the start of the generated data.

The P_ hash algorithm is defined as follows:

P_HASH(secret, seed) = HMAC_HASH(secret, A(1) + seed) +

HMAC_HASH(secret, A(2) + seed) +

HMAC_HASH(secret, A(3) + seed) + ...

Where A(n) is defined as:

A(0) = seed

A(n) = HMAC_HASH(secret, A(n-1))

+ indicates that the results are appended to previous results.

Where ‘HASH’ is a hash function such as SHA256. The hash function to use depends on the SecurityPolicyUri.

The contents of the MessageChunkshall not be interpreted until the Messageis decrypted and the signature and sequence number verified.

If an error occurs during Messageverification the receiver shall close the communication channel. If the receiver is the Server,it shall also send a transport error Messagebefore closing the channel. Once the channel is closed the Clientshall attempt to re-open the channel and request a new SecurityTokenby sending an OpenSecureChannelrequest. The mechanism for sending transport errors to the Clientdepends on the communication channel.

The receiver shall first check the SecureChannelId. This value may be 0 if the Messageis an OpenSecureChannelrequest. For other Messages,it shall report a Bad_SecureChannelUnknownerror if the SecureChannelIdis not recognized. If the Messageis an OpenSecureChannelrequest and the SecureChannelIdis not 0 then the SenderCertificateshall be the same as the SenderCertificateused to create the channel.

If the Messageis secured with asymmetric algorithms, then the receiver shall verify that it supports the requested SecurityPolicy. If the Messageis the response sent to the Client,then the SecurityPolicyshall be the same as the one specified in the request. In the Server,the SecurityPolicyshall be the same as the one used to originally create the SecureChannel.

The receiver shall verify the ReceiverCertificateThumbprintand report a Bad_CertificateInvalid error if it does not recognize it.

The receiver shall check that the Certificateis trusted first and return Bad_SecurityChecksFailedon error. The receiver shall then verify the SenderCertificateusing the rules defined in OPC 10000-4. The receiver shall report the appropriate error if Certificatevalidation fails.

If the Messageis secured with symmetric algorithms, then a Bad_SecureChannel TokenUnknown error shall be reported if the TokenId refers to a SecurityTokenthat has expired or is not recognized.

If decryption or signature validation fails, then a Bad_SecurityChecksFailederror is reported. If an implementation allows multiple SecurityModesto be used the receiver shall also verify that the Messagewas secured properly as required by the SecurityModespecified in the OpenSecureChannelrequest.

After the security validation is complete the receiver shall verify the RequestIdand the SequenceNumber. If these checks fail a Bad_SecurityChecksFailederror is reported. The RequestId only needs to be verified by the Clientsince only the Clientknows if it is valid or not. If the SequenceNumberis not valid, the receiver shall log a Bad_SequenceNumberInvaliderror.

At this point the SecureChannelknows it is dealing with an authenticated Messagethat was not tampered with or resent. This means the SecureChannelcan return secured error responses if any further problems are encountered.

Stacksthat implement UASC shall have a mechanism to log errors when invalid Messagesare discarded. This mechanism is intended for developers, systems integrators and administrators to debug network system configuration issues and to detect attacks on the network.