How an OPC UA Client Connects: Secure Channel, Session, and Read, Packet by Packet
This walkthrough uses opcua-signed.pcapng from the Wireshark project's test captures, in the Wireshark GitLab repository under test/captures/. It was added in October 2023 with the OPC UA dissector's decryption support. We decoded it with VisualEther, which turns a Wireshark PCAP into a sequence diagram with a plain-English caption on every message.
OPC UA (Open Platform Communications Unified Architecture) is how PLCs, SCADA systems, historians, and MES software read and write each other's data. A client never just opens a socket and asks for a value. It first agrees on buffer sizes, then opens a secure channel with an RSA handshake, then creates and activates a session, and only then reads. Each of those steps is visible on the wire, and each answers a question that controls engineers and network engineers both run into.
This capture holds one OPC UA client connecting to a demo server built on the Unified Automation C++ SDK, three times. Each connection runs the full lifecycle: TCP, Hello and Acknowledge, OpenSecureChannel, CreateSession, ActivateSession, two Reads, CloseSession, and CloseSecureChannel. The security policy is Basic256Sha256 with messages signed but not encrypted, so the handshake is unreadable while every service call is in plain view. The second Read returns 180 kB, which arrives in three chunks.
The first connection, TCP stream 0 (frames 1 to 33), is drawn as an annotated sequence diagram. The other two repeat it exactly, except for the TCP ports, the timestamps, the per-connection random values (SecureChannelId, AuthenticationToken, nonces, and signatures), and TCP flow control: the third connection briefly hits a zero window.
Each participant gets a lane, and each message is an arrow, numbered as in Wireshark and captioned with what it does. Under each arrow are the fields that matter: chunk type, SecureChannelId, TokenId, sequence number, RequestId, and for each service its own parameters.
๐ก Read the walkthrough and the diagram side by side: open the interactive diagram in a split-screen window, or open it in a new tab and snap the two windows side by side.
What does OPC UA look like on the wire?
OPC UA has several transports. This capture uses the common one for devices and controllers, OPC UA Binary over TCP, with URLs that start opc.tcp://. It stacks three layers on TCP, all defined in OPC UA Part 6, Mappings, and Part 4, Services:
| Layer | Messages | Job | Secured? |
|---|---|---|---|
| UA Connection Protocol (UACP) | HEL, ACK, ERR | Agree on buffer and message sizes for this TCP connection | Never |
| UA Secure Conversation (UASC) | OPN, MSG, CLO | Open, use, and close a secure channel; split messages into chunks | OPN asymmetrically, MSG and CLO with symmetric keys |
| Services | CreateSession, ActivateSession, Read, CloseSession, โฆ | The application requests and responses | Carried inside MSG |
Every message starts with an 8-byte header: a three-letter type (HEL, OPN, MSGโฆ), a one-letter chunk type, and the message size (Part 6 ยง7.1.2.2). OPN, MSG, and CLO add the 4-byte SecureChannelId, for a 12-byte header (ยง6.7.2.2). The chunk type is F for the final or only chunk, C for an intermediate chunk, and A for a final chunk that aborts the message.
This article cites OPC UA specification version 1.05, free to read at reference.opcfoundation.org.
How does an OPC UA client connect, from TCP to a usable session?
In four nested steps. TCP comes first; then Hello and Acknowledge; then a secure channel; then a session inside the channel. Only a session can call services such as Read. The capture's first connection takes 35 ms from the TCP SYN to an active session.
Hello and Acknowledge: agreeing on chunk sizes
The client's first message, HEL in frame 4, is never secured. It tells the server the largest chunk the client will receive and send (ReceiveBufferSize and SendBufferSize, 65,536 bytes each), the largest whole message (MaxMessageSize, 655,360), the most chunks per message (MaxChunkCount, 10), and the endpoint URL it wants. The server's ACK in frame 6 returns its own limits, here the same values (Part 6 ยง7.1.2.3 and ยง7.1.2.4).
If the server can't accept the request, it sends ERR with a status code and reason and closes the connection. The 65,536-byte chunk limit agreed here explains the three chunks later on.
What is the difference between a secure channel and a session?
A secure channel protects messages between two applications; a session identifies the client and its user to the server. The channel is the communication layer's job, the session the application's (Part 4 ยง5.6.1, and Part 2 ยง4.5.2).
| Secure channel | Session | |
|---|---|---|
| Opened by | OPN OpenSecureChannel (frames 8 and 9) | CreateSession and ActivateSession (frames 10 to 13) |
| Proves | The two application instances, by their X.509 application certificates | The client application, and the user (here anonymous) |
| Provides | Symmetric keys that sign, and optionally encrypt, every message | A context for service calls: subscriptions, continuation points, the user's rights |
| Identified on the wire by | SecureChannelId and TokenId in every MSG header | AuthenticationToken in every request header |
| Lifetime | One TCP connection; keys renewed by a new OPN before the token expires | Can outlive a channel: a client can reactivate it on a new channel after a reconnect |
| Closed by | CLO (frame 30) | CloseSession (frames 28 and 29) |
CreateSession in frame 10 carries the client's certificate, a 32-byte client nonce, and a requested timeout of 1,200,000 ms (20 minutes). The response in frame 11 gives the session two identifiers. The SessionId, ns=1;i=256, is public: it appears in audit logs and the server's diagnostics. The AuthenticationToken is secret, and the client must put it in the header of every later request (Part 4 ยง5.7.2 and ยง7.35). The response also lists the server's endpoints. It offers two, both with Basic256Sha256: SignAndEncrypt with a SecurityLevel of 115 and Sign with 65. A higher SecurityLevel means a more secure endpoint, relative to this server's others only (Part 4 ยง7.14).
A new session can't call services yet. In ActivateSession, frame 12, the client signs the server's certificate and nonce with its own private key, proving it holds the key behind the certificate it sent. It also names the user. Here the UserIdentityToken is empty, which the server treats as anonymous, although it advertised username and X.509 user tokens too. Part 4 ยง5.7.3 is explicit: "Null or empty user token shall always be interpreted as anonymous." The session is active from frame 13.
Why is OpenSecureChannel unreadable when the rest is readable?
Because OPC UA encrypts OPN messages whenever the security mode is not None. Part 6 ยง6.7.4 says so directly: "The OpenSecureChannel Messages are signed and encrypted if the SecurityMode is not None (even if the SecurityMode is Sign)." Wireshark shows both OPN messages, frames 8 and 9, as "(encrypted)", and decodes every MSG after them.
The reason is the key exchange. OPN carries a random nonce from each side, and both ends derive the channel's symmetric signing and encryption keys from those two nonces alone. Anyone who saw both nonces could compute the keys and forge signed messages. So the OPN body is encrypted with the receiver's RSA public key and signed with the sender's RSA private key, and only the message header and the asymmetric security header (Part 6 ยง6.7.2.3) stay in the clear, because the receiver needs them to find the right keys:
Frame 8: client to server, OPN (OpenSecureChannel request)
Message Type: OPN
Chunk Type: F
Message Size: 2017
SecureChannelId: 0
SecurityPolicyUri: http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256
SenderCertificate: (the client's X.509 certificate, 1,404 bytes)
ReceiverCertificateThumbprint: e4d6c33fb48eae530855c8ab17552ef3f3372d72
(everything after this point is encrypted)
SecureChannelId 0 means the client has no channel yet. The SenderCertificate is the client's application certificate, and ReceiverCertificateThumbprint is the SHA-1 thumbprint of the server certificate it encrypted to. Frame 9 mirrors it: the server's certificate, the client's thumbprint, and the new SecureChannelId, 2212364288. The encrypted body also holds the security token, TokenId 1, with its lifetime.
Basic256Sha256 names the algorithms (Part 7 v1.04 ยง6.6.165; version 1.05 publishes the policies on the OPC Foundation profiles site): RSA-OAEP with SHA-1 for the asymmetric encryption, RSA with SHA-256 for asymmetric signatures, HMAC-SHA256 for symmetric signatures, and AES-256-CBC for symmetric encryption. The server took 6.9 ms to answer, a delay consistent with its RSA work.
What does "signed, not encrypted" protect, and what does it leave visible?
Signing protects integrity and authenticity: every MSG ends with a 32-byte HMAC-SHA256 signature computed with the channel's keys, so a changed, injected, or replayed message fails the check. It does nothing for confidentiality. The capture proves the mode by what it shows: CreateSessionRequest in frame 10 is readable plaintext followed by a Security Signature, where SignAndEncrypt would show ciphertext as OPN does. The channel runs MessageSecurityMode Sign: "All messages are signed but not encrypted" (Part 4 ยง7.20; Part 2 ยง4.8 describes the modes).
| An eavesdropper can read | Protected from change, but readable | Kept secret |
|---|---|---|
| Endpoint URL, policy, and both certificates | Every service request and response | The nonces and the derived channel keys |
| SecureChannelId, TokenId, sequence numbers, RequestIds | Node IDs read and the values returned | The private keys |
| Session IDs and the AuthenticationToken | Session timeouts and status codes |
The AuthenticationToken is the uncomfortable entry. With Sign, it crosses the wire in the clear in every request. An attacker who reads it still can't use it on another channel: the server checks the token together with the SecureChannelId, and moving a session to a new channel takes an ActivateSession signed with the client's private key (Part 4 ยง5.7.2 and ยง5.7.3). What Sign gives up is confidentiality: anyone on the path sees which nodes the client reads and every value. Sign suits networks where integrity matters and the data is not sensitive; SignAndEncrypt is the safer default. Compare MQTT over TLS, where TLS encrypts the whole stream and leaves only the server name, sizes, and timing to see.
Frame 14 is a ReadRequest asking for three values. The sequence header and the NodesToRead list are both plain:
frame : Frame 14: Packet, 230 bytes on wire (1840 bits), 230 bytes captured (1840 bits) on interface lo, id 0
Interface id : 0 (lo)
eth : Ethernet II, Src: 00:00:00:00:00:00, Dst: 00:00:00:00:00:00
Destination : 00:00:00:00:00:00
Source : 00:00:00:00:00:00
ip : Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.1.1
Differentiated Services Field : 0x00 (DSCP: CS0, ECN: Not-ECT)
010. .... = Flags : 0x2, Don't fragment
tcp : Transmission Control Protocol, Src Port: 50580, Dst Port: 4840, Seq: 4264, Ack: 10464, Len: 164
Conversation completeness : Incomplete, DATA (15)
Flags : 0x018 (PSH, ACK)
Options : (12 bytes), No-Operation (NOP), No-Operation (NOP), Timestamps
TCP Option - No-Operation (NOP)
TCP Option - No-Operation (NOP)
TCP Option - Timestamps : TSval 3818337279, TSecr 2378431460
Timestamps
SEQ/ACK analysis
opcua : OpcUa Binary Protocol
Message : Encodeable Object
TypeId : ExpandedNodeId
ReadRequest
RequestHeader : RequestHeader
AuthenticationToken : NodeId
Return Diagnostics : 0x00000000
AdditionalHeader : ExtensionObject
TypeId : NodeId
EncodingMask : 0x00
NodesToRead : Array of ReadValueId
[0] : ReadValueId
NodeId : NodeId
DataEncoding : QualifiedName
[1] : ReadValueId
NodeId : NodeId
DataEncoding : QualifiedName
[2] : ReadValueId
NodeId : NodeId
DataEncoding : QualifiedName
Frame 14, ReadRequest. Under OpcUa: the message header with the SecureChannelId, the symmetric security header (Security Token Id 1), the sequence header (Sequence Number 1026, RequestId 4), the RequestHeader with the AuthenticationToken and RequestHandle 1000003, then MaxAge 0, TimestampsToReturn Both, and three ReadValueIds, each attribute 13 (Value), followed by the 32-byte Security Signature.
The three nodes are standard ones every OPC UA server has, in namespace 0: i=2255 is Server_NamespaceArray, i=2259 Server_ServerStatus_State, and i=2992 Server_ServerStatus_SecondsTillShutdown. The response in frame 15 returns the namespace list, the state 0 (Running), and 0 seconds till shutdown.
Sequence numbers and RequestIds
Two counters in the sequence header do different jobs (Part 6 ยง6.7.2.4). The SequenceNumber counts chunks: the sender assigns it and adds exactly one for every chunk, so each direction has its own count, and a missing, repeated, or reordered chunk is detectable. The RequestId pairs a request with its response, and every chunk of one message shares it.
The client's first MSG is sequence number 1024 with RequestId 2; the OPN before it, inside the encrypted part, was almost certainly RequestId 1. By the end, the client is at 1029 and the server at 1030. The server is one ahead because its chunked response used three sequence numbers for one RequestId.
How does OPC UA split a large response into chunks?
Any message bigger than the agreed buffer size is cut into chunks, each a complete, separately secured OPC UA message with its own headers and signature. Part 6 ยง6.7.1 puts it plainly: "All security is applied to individual MessageChunks and not the entire OPC UA Message." The second ReadRequest, frame 16, asks for one node, i=7617, OpcUa_BinarySchema: the XML dictionary describing how every standard OPC UA type is encoded. The response is 179,945 bytes, almost three times the 65,536-byte chunk limit, so the server sends it in three chunks:
| Frame | Chunk type | Chunk size | SequenceNumber | RequestId | Body bytes |
|---|---|---|---|---|---|
| 18 | C, intermediate | 65,536 | 1027 | 5 | 65,480 |
| 22 | C, intermediate | 65,536 | 1028 | 5 | 65,480 |
| 27 | F, final | 49,041 | 1029 | 5 | 48,985 |
Each chunk spends 56 bytes on overhead: a 12-byte message header (type, chunk type, size, and SecureChannelId), a 4-byte security header (the TokenId), an 8-byte sequence header, and the 32-byte signature. With Sign there is no padding (Part 6 ยง6.7.2). Signing each chunk lets the receiver verify every piece as it arrives, before it has the whole message. The receiver reassembles the bodies in sequence-number order and decodes the service only after the F chunk. Wireshark does the same: frames 18 and 22 show no service name, and frame 27 shows the full ReadResponse.
frame : Frame 27: Packet, 16339 bytes on wire (130712 bits), 16339 bytes captured (130712 bits) on interface lo, id 0
Interface id : 0 (lo)
eth : Ethernet II, Src: 00:00:00:00:00:00, Dst: 00:00:00:00:00:00
Destination : 00:00:00:00:00:00
Source : 00:00:00:00:00:00
ip : Internet Protocol Version 4, Src: 127.0.1.1, Dst: 127.0.0.1
Differentiated Services Field : 0x00 (DSCP: CS0, ECN: Not-ECT)
010. .... = Flags : 0x2, Don't fragment
tcp : Transmission Control Protocol, Src Port: 4840, Dst Port: 50580, Seq: 174585, Ack: 4556, Len: 16273
Conversation completeness : Incomplete, DATA (15)
Flags : 0x018 (PSH, ACK)
Options : (12 bytes), No-Operation (NOP), No-Operation (NOP), Timestamps
TCP Option - No-Operation (NOP)
TCP Option - No-Operation (NOP)
TCP Option - Timestamps : TSval 2378431490, TSecr 3818337309
Timestamps
SEQ/ACK analysis
fake-field-wrapper : fake-field-wrapper
2 Reassembled TCP Segments (49041 bytes) : #24(32768), #27(16273)
opcua : OpcUa Binary Protocol
3 Message fragments (179945 bytes) : #18(65480), #22(65480), #27(48985)
Message : Encodeable Object
TypeId : ExpandedNodeId
ReadResponse
ResponseHeader : ResponseHeader
ServiceDiagnostics : DiagnosticInfo
EncodingMask : 0x00
StringTable : Array of String
AdditionalHeader : ExtensionObject
TypeId : NodeId
EncodingMask : 0x00
Results : Array of DataValue
[0] : DataValue
EncodingMask : 0x0d, has value, has source timestamp, has server timestamp
Value : Variant
DiagnosticInfos : Array of DiagnosticInfo
Frame 27, the final chunk. Under OpcUa: Message Type MSG, Chunk Type F, Message Size 49041, Sequence Number 1029, RequestId 5, then Wireshark's reassembly list (frames 18, 22, and 27, 179,945 bytes) and the decoded ReadResponse: RequestHandle 1000004, ServiceResult Good, and one DataValue holding a ByteString, the binary schema.
The limits from Hello and Acknowledge still apply. Three chunks is within the MaxChunkCount of 10, and 179,945 bytes is within the MaxMessageSize of 655,360. A larger response would fail with an error status instead of being sent. If a sender has to give up partway through, it sends a final chunk of type A, carrying an error code and reason, to abort the message (Part 6 ยง6.7.3).
Under the chunks, TCP is busy too. Each 65,536-byte chunk crosses the loopback interface as two 32,768-byte segments, and Wireshark marks some of them "TCP Window Full": the server filled the client's advertised receive window before the client acknowledged. That is normal TCP flow control on a fast link, not loss. The third connection in the capture goes one step further and briefly advertises a zero window.
How does the connection close?
In reverse order: session first, then channel, then TCP. CloseSessionRequest in frame 28 still carries the AuthenticationToken, with DeleteSubscriptions set to True so the server drops any subscriptions the session owned (Part 4 ยง5.7.4). After CloseSessionResponse in frame 29, the channel is still open, and the client could create another session on it.
CLO in frame 30 closes the channel. It is a request with no response: the server releases the channel and its keys (Part 6 ยง7.1.4). The spec has the client close the socket after sending CLO, and ยง7.1.5 has the server close the connection when it receives one. Here the server is faster: its FIN follows 43 ยตs later, in frame 31, and the client's FIN comes next. From SYN to the last ACK, the whole lifecycle takes 76 ms.
Which port does OPC UA use, and what does a firewall need to allow?
TCP port 4840, registered with IANA as opcua-tcp, and the port in this capture. IANA also registers 4843 for OPC UA over TLS. Many servers listen on other ports, so check the endpoint URL (opc.tcp://host:port). A firewall or ACL needs to allow:
- The client to the server's TCP port, with the client opening the connection. The server never connects back; replies use the same connection.
- The discovery endpoint, if clients use it. Clients often call GetEndpoints first, usually on the same port; a Local Discovery Server, if one runs, listens on 4840.
- Long-lived connections. A session can last for hours and go quiet for minutes; here the client asked for a 20-minute session timeout. A firewall idle timeout that drops a quiet connection breaks the channel, and the symptom is an unexplained reconnect. Clients usually keep the connection busy with periodic reads or subscription traffic.
- Large messages. Chunks of 64 kB and messages of hundreds of kilobytes are normal, so deep-packet inspection must reassemble chunks before it parses services.
For inspection, the security mode decides what a firewall can see. With None or Sign, an OPC UAโaware firewall can read every service and node ID and enforce rules such as "read only, no Write or Call". With SignAndEncrypt, it sees only the transport headers: endpoint, policy, certificates, SecureChannelId, TokenId, and chunk sizes. Allow-listing by certificate thumbprint works in every mode, because OPN always carries the certificates in the clear.
How to debug an OPC UA connection in Wireshark
- Filter on
opcua. Wireshark decodes port 4840 automatically. For another port, use Decode As to map the TCP port to OpcUa. - Follow the message types.
opcua.transport.typegivesHEL,ACK,ERR,OPN,MSG,CLO. A connection that stops afterHEL, or ends inERR, failed below the secure channel; read theERRstatus code. - Check the policy and certificates in
OPN. A server that rejects the client certificate answers theOPNwith anERRand closes the connection, so the status code in thatERRnames the problem. - Watch the service results.
opcua.ServiceResulton each response is the first status to check; a Good service result can still hold Bad status codes for individual nodes. - Expect to see nothing under
SignAndEncrypt. Wireshark's OPC UA dissector can decrypt it only with the channel keys from a key log, set in theopcua.debug_filepreference.
FAQ
What port does OPC UA use? TCP 4840 by default, as opc.tcp://host:4840, though servers can use any port. The endpoint URL names it.
What is the difference between an OPC UA secure channel and a session? The secure channel secures messages between two applications, using their certificates and keys derived during OpenSecureChannel. The session identifies the client application and user to the server and carries the context for service calls. A session runs inside a channel and can move to a new one after a reconnect.
Why does Wireshark show OpenSecureChannel as encrypted? OPC UA encrypts OpenSecureChannel with the receiver's RSA public key whenever the security mode is Sign or SignAndEncrypt, because the nonces inside it are the inputs to the channel keys.
What does MessageSecurityMode Sign do? It adds an HMAC signature to every message so changes and forgeries are detected, but leaves the content readable. SignAndEncrypt also encrypts the content.
What is Basic256Sha256? An OPC UA security policy: RSA (2048- to 4096-bit keys) with SHA-256 signatures and OAEP encryption for the handshake, and HMAC-SHA256 and AES-256-CBC with the channel keys afterward.
What do the OPC UA chunk types F, C, and A mean? F is the final, or only, chunk of a message; C is an intermediate chunk with more to follow; A is a final chunk that aborts the message.
What is the AuthenticationToken? A secret the server returns in CreateSessionResponse. The client puts it in every request header to say which session the request belongs to.
Takeaways
- Four layers of setup before the first read. TCP, Hello and Acknowledge, the secure channel, then a created and activated session.
- Hello and Acknowledge set the chunk size. Here 65,536 bytes, which later splits a 180 kB response into three chunks.
- OpenSecureChannel is always encrypted unless security is off. Its nonces are the inputs to the channel keys; only the policy, certificates, and thumbprint stay readable.
- Sign is not encrypt. Every service call, node ID, value, and the AuthenticationToken are readable; they just can't be changed undetected.
- The channel and the session have separate identifiers.
SecureChannelIdandTokenIdmark every message; theAuthenticationTokenmarks every session request. - Chunks are messages in their own right. Each has its own headers, sequence number, and signature, and all share one RequestId.
- For firewalls: one inbound TCP port, long-lived connections, and large messages. What an inspecting firewall can see depends on the security mode.