Coverage Report

Created: 2026-10-05 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/open62541_15/src/ua_securechannel.c
Line
Count
Source
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this
3
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
 *
5
 *    Copyright 2014-2020 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
6
 *    Copyright 2014, 2016-2017 (c) Florian Palm
7
 *    Copyright 2015-2016 (c) Sten GrĂ¼ner
8
 *    Copyright 2015 (c) Oleksiy Vasylyev
9
 *    Copyright 2016 (c) TorbenD
10
 *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
11
 *    Copyright 2017-2018 (c) Mark Giraud, Fraunhofer IOSB
12
 *    Copyright 2018-2019 (c) HMS Industrial Networks AB (Author: Jonas Green)
13
 *    Copyright 2025 (c) o6 Automation GmbH (Author: Julius Pfrommer)
14
 *    Copyright 2026 (c) o6 Automation GmbH (Author: Andreas Ebner)
15
 */
16
17
#include <open62541/types.h>
18
#include <open62541/transport_generated.h>
19
20
#include "ua_securechannel.h"
21
#include "ua_types_encoding_binary.h"
22
23
2.27k
#define UA_BITMASK_MESSAGETYPE 0x00ffffffu
24
2.27k
#define UA_BITMASK_CHUNKTYPE 0xff000000u
25
26
const UA_String UA_SECURITY_POLICY_NONE_URI =
27
    {47, (UA_Byte *)"http://opcfoundation.org/UA/SecurityPolicy#None"};
28
29
void
30
13.2k
UA_SecureChannel_init(UA_SecureChannel *channel) {
31
    /* Normal linked lists are initialized by zeroing out */
32
13.2k
    memset(channel, 0, sizeof(UA_SecureChannel));
33
13.2k
    TAILQ_INIT(&channel->chunks);
34
13.2k
}
35
36
UA_StatusCode
37
UA_SecureChannel_setSecurityPolicy(UA_SecureChannel *channel, UA_SecurityPolicy *sp,
38
3.29k
                                   const UA_ByteString *remoteCertificate) {
39
    /* Is a policy already configured? */
40
3.29k
    UA_CHECK_ERROR(!channel->securityPolicy, return UA_STATUSCODE_BADINTERNALERROR,
41
3.29k
                   sp->logger, UA_LOGCATEGORY_SECURITYPOLICY,
42
3.29k
                   "Security policy already configured");
43
44
    /* Create the context */
45
3.29k
    UA_StatusCode res = sp->newChannelContext(sp, remoteCertificate,
46
3.29k
                                              &channel->channelContext);
47
3.29k
    res |= UA_ByteString_copy(remoteCertificate, &channel->remoteCertificate);
48
3.29k
    UA_CHECK_STATUS_ERROR(res, return res, sp->logger, UA_LOGCATEGORY_SECURITYPOLICY,
49
3.29k
                          "Could not set up the SecureChannel context");
50
51
    /* Compute the certificate thumbprint */
52
3.29k
    UA_ByteString remoteCertificateThumbprint =
53
3.29k
        {20, channel->remoteCertificateThumbprint};
54
3.29k
    res = sp->makeCertThumbprint(sp, &channel->remoteCertificate,
55
3.29k
                                 &remoteCertificateThumbprint);
56
3.29k
    UA_CHECK_STATUS_ERROR(res, return res, sp->logger, UA_LOGCATEGORY_SECURITYPOLICY,
57
3.29k
                          "Could not create the certificate thumbprint");
58
59
    /* Set the SecurityPolicy and cache the URI-derived properties (the policy
60
     * is fixed for the channel's lifetime). */
61
3.29k
    channel->securityPolicy = sp;
62
3.29k
    channel->enhancedSecurity = UA_SecurityPolicy_isEnhancedSecurity(sp);
63
3.29k
    channel->legacySequenceNumbers = UA_SecurityPolicy_useLegacySequenceNumbers(sp);
64
65
    /* Set a temporary SecurityMode. The client sets the final SecurityMode
66
     * right after. The server only after fully decoding the OPN message in the
67
     * OpenSecureChannel service. But we need the SecurityMode for decoding. The
68
     * OPN message is always signed and encrypted when not #None. */
69
3.29k
    if(sp->policyType == UA_SECURITYPOLICYTYPE_NONE)
70
3.29k
        channel->securityMode = UA_MESSAGESECURITYMODE_NONE;
71
0
    else
72
0
        channel->securityMode = UA_MESSAGESECURITYMODE_SIGNANDENCRYPT;
73
3.29k
    return UA_STATUSCODE_GOOD;
74
3.29k
}
75
76
/* The #None SecurityPolicy must use the NONE SecurityMode. All other
77
 * SecurityPolicies must not. */
78
UA_StatusCode
79
UA_SecureChannel_setSecurityMode(UA_SecureChannel *channel,
80
0
                                 UA_MessageSecurityMode securityMode) {
81
0
    if(securityMode == UA_MESSAGESECURITYMODE_INVALID ||
82
0
       (UA_UInt32)securityMode > UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
83
0
        return UA_STATUSCODE_BADSECURITYMODEREJECTED;
84
0
    UA_SecurityPolicy *sp = channel->securityPolicy;
85
0
    if(!sp)
86
0
        return UA_STATUSCODE_BADSECURITYMODEREJECTED;
87
0
    UA_Boolean isNonePolicy = (sp->policyType == UA_SECURITYPOLICYTYPE_NONE);
88
0
    UA_Boolean isNoneMode = (securityMode == UA_MESSAGESECURITYMODE_NONE);
89
0
    if(isNonePolicy != isNoneMode)
90
0
        return UA_STATUSCODE_BADSECURITYMODEREJECTED;
91
0
    channel->securityMode = securityMode;
92
0
    return UA_STATUSCODE_GOOD;
93
0
}
94
95
/* Hides some errors before sending them to a client according to the
96
 * standard. */
97
static void
98
2.13k
hideErrors(UA_TcpErrorMessage *const error) {
99
2.13k
    switch(error->error) {
100
0
    case UA_STATUSCODE_BADCERTIFICATEINVALID:
101
0
    case UA_STATUSCODE_BADCERTIFICATECHAININCOMPLETE:
102
0
    case UA_STATUSCODE_BADCERTIFICATEPOLICYCHECKFAILED:
103
0
    case UA_STATUSCODE_BADCERTIFICATEUNTRUSTED:
104
0
    case UA_STATUSCODE_BADCERTIFICATEREVOCATIONUNKNOWN:
105
0
    case UA_STATUSCODE_BADCERTIFICATEISSUERREVOCATIONUNKNOWN:
106
0
    case UA_STATUSCODE_BADCERTIFICATEREVOKED:
107
0
    case UA_STATUSCODE_BADCERTIFICATEISSUERREVOKED:
108
0
    case UA_STATUSCODE_BADCERTIFICATEISSUERUSENOTALLOWED:
109
0
        error->error = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
110
0
        error->reason = UA_STRING_NULL;
111
0
        break;
112
        // TODO: Check if these are all cases that need to be covered.
113
2.13k
    default:
114
2.13k
        break;
115
2.13k
    }
116
2.13k
}
117
118
UA_Boolean
119
7.90k
UA_SecureChannel_isConnected(UA_SecureChannel *channel) {
120
7.90k
    return (channel->state > UA_SECURECHANNELSTATE_CLOSED &&
121
7.90k
            channel->state < UA_SECURECHANNELSTATE_CLOSING);
122
7.90k
}
123
124
void
125
951
UA_SecureChannel_sendERR(UA_SecureChannel *channel, UA_TcpErrorMessage *error) {
126
951
    if(!UA_SecureChannel_isConnected(channel))
127
198
        return;
128
129
753
    hideErrors(error);
130
131
753
    UA_TcpMessageHeader header;
132
753
    header.messageTypeAndChunkType = UA_MESSAGETYPE_ERR + UA_CHUNKTYPE_FINAL;
133
    /* Header + ErrorMessage (error + reasonLength_field + length) */
134
753
    header.messageSize = 8 + (4 + 4 + (UA_UInt32)error->reason.length);
135
136
    /* Get the send buffer from the network layer */
137
753
    UA_ConnectionManager *cm = channel->connectionManager;
138
753
    UA_ByteString msg = UA_BYTESTRING_NULL;
139
753
    UA_StatusCode retval = cm->allocNetworkBuffer(cm, channel->connectionId,
140
753
                                                  &msg, header.messageSize);
141
753
    if(retval != UA_STATUSCODE_GOOD)
142
0
        return;
143
144
    /* Encode and send the response */
145
753
    UA_Byte *bufPos = msg.data;
146
753
    const UA_Byte *bufEnd = &msg.data[msg.length];
147
753
    retval |= UA_encodeBinaryInternal(&header,
148
753
                                      &UA_TRANSPORT[UA_TRANSPORT_TCPMESSAGEHEADER],
149
753
                                      &bufPos, &bufEnd, NULL, NULL, NULL);
150
753
    retval |= UA_encodeBinaryInternal(error,
151
753
                                      &UA_TRANSPORT[UA_TRANSPORT_TCPERRORMESSAGE],
152
753
                                      &bufPos, &bufEnd, NULL, NULL, NULL);
153
753
    (void)retval; /* Encoding of these cannot fail */
154
753
    msg.length = header.messageSize;
155
753
    cm->sendWithConnection(cm, channel->connectionId, &UA_KEYVALUEMAP_NULL, &msg);
156
753
}
157
158
static void
159
0
UA_Chunk_delete(UA_Chunk *chunk) {
160
0
    if(chunk->copied)
161
0
        UA_ByteString_clear(&chunk->bytes);
162
0
    UA_free(chunk);
163
0
}
164
165
static void
166
13.2k
deleteChunks(UA_SecureChannel *channel) {
167
13.2k
    UA_Chunk *chunk, *chunk_tmp;
168
13.2k
    TAILQ_FOREACH_SAFE(chunk, &channel->chunks, pointers, chunk_tmp) {
169
0
        TAILQ_REMOVE(&channel->chunks, chunk, pointers);
170
0
        UA_Chunk_delete(chunk);
171
0
    }
172
13.2k
    channel->chunksCount = 0;
173
13.2k
    channel->chunksLength = 0;
174
13.2k
}
175
176
void
177
13.2k
UA_SecureChannel_deleteBuffered(UA_SecureChannel *channel) {
178
13.2k
    deleteChunks(channel);
179
13.2k
    if(channel->unprocessedCopied)
180
1.90k
        UA_ByteString_clear(&channel->unprocessed);
181
13.2k
}
182
183
void
184
UA_SecureChannel_shutdown(UA_SecureChannel *channel,
185
985
                          UA_ShutdownReason shutdownReason) {
186
    /* No open socket or already closing -> nothing to do */
187
985
    if(!UA_SecureChannel_isConnected(channel))
188
198
        return;
189
190
    /* Set the shutdown event for diagnostics */
191
787
    channel->shutdownReason= shutdownReason;
192
193
    /* Trigger the async closing of the connection */
194
787
    UA_ConnectionManager *cm = channel->connectionManager;
195
787
    cm->closeConnection(cm, channel->connectionId);
196
787
    channel->state = UA_SECURECHANNELSTATE_CLOSING;
197
787
}
198
199
void
200
6.37k
UA_SecureChannel_clear(UA_SecureChannel *channel) {
201
    /* No sessions must be attached to this any longer */
202
6.37k
    UA_assert(channel->sessions == NULL);
203
204
    /* Delete the channel context for the security policy */
205
6.37k
    UA_SecurityPolicy *sp = channel->securityPolicy;
206
6.37k
    if(sp) {
207
3.29k
        sp->deleteChannelContext(sp, channel->channelContext);
208
3.29k
        channel->securityPolicy = NULL;
209
3.29k
        channel->channelContext = NULL;
210
3.29k
        channel->enhancedSecurity = false;     /* No policy => not enhanced */
211
3.29k
        channel->legacySequenceNumbers = true; /* No policy => legacy */
212
3.29k
    }
213
214
    /* Remove remaining delayed callback */
215
6.37k
    if(channel->connectionManager &&
216
4.31k
       channel->connectionManager->eventSource.eventLoop) {
217
144
        UA_EventLoop *el = channel->connectionManager->eventSource.eventLoop;
218
144
        el->removeDelayedCallback(el, &channel->unprocessedDelayed);
219
144
    }
220
221
    /* The EventLoop connection is no longer valid */
222
6.37k
    channel->connectionId = 0;
223
6.37k
    channel->connectionManager = NULL;
224
225
    /* Clean up the SecurityToken */
226
6.37k
    UA_ChannelSecurityToken_clear(&channel->securityToken);
227
6.37k
    UA_ChannelSecurityToken_clear(&channel->altSecurityToken);
228
229
    /* Clean up certificate and nonces */
230
6.37k
    UA_ByteString_clear(&channel->remoteCertificate);
231
6.37k
    UA_ByteString_clear(&channel->localNonce);
232
6.37k
    UA_ByteString_clear(&channel->remoteNonce);
233
234
    /* Clean up the v1.05.07 SecureChannel elements */
235
6.37k
    UA_ByteString_clear(&channel->firstRequestSignature);
236
6.37k
    UA_ByteString_clear(&channel->currentIKM);
237
6.37k
    UA_ByteString_clear(&channel->channelThumbprint);
238
239
    /* Clean up endpointUrl and remoteAddress */
240
6.37k
    UA_String_clear(&channel->endpointUrl);
241
6.37k
    UA_String_clear(&channel->remoteAddress);
242
243
    /* Delete remaining chunks */
244
6.37k
    UA_SecureChannel_deleteBuffered(channel);
245
246
    /* Clean up namespace mapping */
247
6.37k
    UA_NamespaceMapping_delete(channel->namespaceMapping);
248
6.37k
    channel->namespaceMapping = NULL;
249
250
    /* Reset the SecureChannel for reuse (in the client) */
251
6.37k
    channel->securityMode = UA_MESSAGESECURITYMODE_INVALID;
252
6.37k
    channel->shutdownReason = UA_SHUTDOWNREASON_CLOSE;
253
6.37k
    memset(&channel->config, 0, sizeof(UA_ConnectionConfig));
254
6.37k
    channel->receiveSequenceNumber = 0;
255
6.37k
    channel->sendSequenceNumber = 0;
256
257
    /* Set the state to closed */
258
6.37k
    channel->state = UA_SECURECHANNELSTATE_CLOSED;
259
6.37k
    channel->renewState = UA_SECURECHANNELRENEWSTATE_NORMAL;
260
6.37k
}
261
262
UA_StatusCode
263
UA_SecureChannel_processHELACK(UA_SecureChannel *channel,
264
137
                               const UA_TcpAcknowledgeMessage *remoteConfig) {
265
    /* The lowest common version is used by both sides */
266
137
    if(channel->config.protocolVersion > remoteConfig->protocolVersion)
267
0
        channel->config.protocolVersion = remoteConfig->protocolVersion;
268
269
    /* Can we receive the max send size? */
270
137
    if(channel->config.sendBufferSize > remoteConfig->receiveBufferSize)
271
38
        channel->config.sendBufferSize = remoteConfig->receiveBufferSize;
272
273
    /* Can we send the max receive size? */
274
137
    if(channel->config.recvBufferSize > remoteConfig->sendBufferSize)
275
38
        channel->config.recvBufferSize = remoteConfig->sendBufferSize;
276
277
137
    channel->config.remoteMaxMessageSize = remoteConfig->maxMessageSize;
278
137
    channel->config.remoteMaxChunkCount = remoteConfig->maxChunkCount;
279
280
    /* Chunks of at least 8192 bytes must be permissible.
281
     * See Part 6, Clause 6.7.1 */
282
137
    if(channel->config.recvBufferSize < 8192 ||
283
119
       channel->config.sendBufferSize < 8192 ||
284
106
       (channel->config.remoteMaxMessageSize != 0 &&
285
99
        channel->config.remoteMaxMessageSize < 8192))
286
39
        return UA_STATUSCODE_BADINTERNALERROR;
287
288
98
    return UA_STATUSCODE_GOOD;
289
137
}
290
291
/* Send an OPN message using asymmetric encryption.
292
 * Specification part 6, 6.7.4: The OpenSecureChannel Messages are signed and
293
 * encrypted if the SecurityMode is not None (even if the SecurityMode is
294
 * SignOnly). */
295
UA_StatusCode
296
UA_SecureChannel_sendOPN(UA_SecureChannel *channel,
297
                         UA_UInt32 requestId, const void *content,
298
0
                         const UA_DataType *contentType) {
299
0
    if(!content || !contentType)
300
0
        return UA_STATUSCODE_BADINTERNALERROR;
301
302
    /* The SecurityPolicy must be configured before sending OPN */
303
0
    const UA_SecurityPolicy *sp = channel->securityPolicy;
304
0
    UA_CHECK_MEM(sp, return UA_STATUSCODE_BADINTERNALERROR);
305
306
    /* Check for a valid security mode */
307
0
    UA_assert(channel->securityMode > UA_MESSAGESECURITYMODE_INVALID &&
308
0
              channel->securityMode <= UA_MESSAGESECURITYMODE_SIGNANDENCRYPT);
309
310
    /* The #None SecurityPolicy must use the NONE MessageSecurityMode.
311
     * All other SecurityPolicies must not. */
312
0
    UA_assert((sp->policyType == UA_SECURITYPOLICYTYPE_NONE) ==
313
0
              (channel->securityMode == UA_MESSAGESECURITYMODE_NONE));
314
315
    /* Can we use the connection manager? */
316
0
    UA_ConnectionManager *cm = channel->connectionManager;
317
0
    if(!UA_SecureChannel_isConnected(channel))
318
0
        return UA_STATUSCODE_BADCONNECTIONCLOSED;
319
320
    /* Allocate the message buffer */
321
0
    UA_ByteString buf = UA_BYTESTRING_NULL;
322
0
    UA_StatusCode res = cm->allocNetworkBuffer(cm, channel->connectionId, &buf,
323
0
                                               channel->config.sendBufferSize);
324
0
    UA_CHECK_STATUS(res, return res);
325
326
    /* Restrict buffer to the available space for the payload */
327
0
    UA_Byte *buf_pos = buf.data;
328
0
    const UA_Byte *buf_end = &buf.data[buf.length];
329
0
    res = hideBytesAsym(channel, &buf_pos, &buf_end);
330
0
    UA_CHECK_STATUS(res, cm->freeNetworkBuffer(cm, channel->connectionId, &buf);
331
0
                    return res);
332
333
    /* Define variables here to pacify some compilers wrt goto */
334
0
    size_t securityHeaderLength, pre_sig_length, total_length, encryptedLength;
335
336
    /* Encode the message type and content */
337
0
    UA_EncodeBinaryOptions encOpts;
338
0
    memset(&encOpts, 0, sizeof(UA_EncodeBinaryOptions));
339
0
    encOpts.namespaceMapping = channel->namespaceMapping;
340
0
    res |= UA_NodeId_encodeBinary(&contentType->binaryEncodingId, &buf_pos, buf_end);
341
0
    res |= UA_encodeBinaryInternal(content, contentType, &buf_pos, &buf_end,
342
0
                                   &encOpts, NULL, NULL);
343
0
    UA_CHECK_STATUS(res, goto error);
344
345
    /* Compute the header length */
346
0
    securityHeaderLength = calculateAsymAlgSecurityHeaderLength(channel);
347
348
    /* Add padding to the chunk */
349
0
    if(channel->securityMode != UA_MESSAGESECURITYMODE_NONE)
350
0
        padChunk(channel, &sp->asymSignatureAlgorithm, &sp->asymEncryptionAlgorithm,
351
0
                 &buf.data[UA_SECURECHANNEL_CHANNELHEADER_LENGTH + securityHeaderLength],
352
0
                 &buf_pos);
353
354
    /* The total message length */
355
0
    pre_sig_length = (uintptr_t)buf_pos - (uintptr_t)buf.data;
356
0
    total_length = pre_sig_length;
357
0
    if(channel->securityMode != UA_MESSAGESECURITYMODE_NONE)
358
0
        total_length += sp->asymSignatureAlgorithm.
359
0
            getLocalSignatureSize(sp, channel->channelContext);
360
361
    /* The total message length is known here which is why we encode the headers
362
     * at this step and not earlier. */
363
0
    res = prependHeadersAsym(channel, buf.data, buf_end, total_length,
364
0
                             securityHeaderLength, requestId, &encryptedLength);
365
0
    UA_CHECK_STATUS(res, goto error);
366
367
    /* Add the signature and encrypt the message */
368
0
    res = signAndEncryptAsym(channel, pre_sig_length, &buf,
369
0
                             securityHeaderLength, total_length);
370
0
    UA_CHECK_STATUS(res, goto error);
371
372
    /* Send the message, the buffer is freed in the network layer */
373
0
    buf.length = encryptedLength;
374
0
    return cm->sendWithConnection(cm, channel->connectionId, &UA_KEYVALUEMAP_NULL, &buf);
375
376
0
 error:
377
0
    cm->freeNetworkBuffer(cm, channel->connectionId, &buf);
378
0
    return res;
379
0
}
380
381
/* Will this chunk surpass the capacity of the SecureChannel for the message? */
382
static UA_StatusCode
383
0
adjustCheckMessageLimitsSym(UA_MessageContext *mc, size_t bodyLength) {
384
0
    mc->messageSizeSoFar += bodyLength;
385
0
    mc->chunksSoFar++;
386
387
0
    UA_SecureChannel *channel = mc->channel;
388
0
    if(mc->messageSizeSoFar > channel->config.localMaxMessageSize &&
389
0
       channel->config.localMaxMessageSize != 0)
390
0
        return UA_STATUSCODE_BADRESPONSETOOLARGE;
391
392
0
    if(mc->chunksSoFar > channel->config.localMaxChunkCount &&
393
0
       channel->config.localMaxChunkCount != 0)
394
0
        return UA_STATUSCODE_BADRESPONSETOOLARGE;
395
396
0
    return UA_STATUSCODE_GOOD;
397
0
}
398
399
static UA_StatusCode
400
0
encodeHeadersSym(UA_MessageContext *mc, size_t totalLength) {
401
0
    UA_SecureChannel *channel = mc->channel;
402
0
    UA_Byte *header_pos = mc->messageBuffer.data;
403
404
0
    UA_TcpMessageHeader header;
405
0
    header.messageTypeAndChunkType = mc->messageType;
406
0
    header.messageSize = (UA_UInt32)totalLength;
407
0
    if(mc->final)
408
0
        header.messageTypeAndChunkType += UA_CHUNKTYPE_FINAL;
409
0
    else
410
0
        header.messageTypeAndChunkType += UA_CHUNKTYPE_INTERMEDIATE;
411
412
0
    UA_SequenceHeader seqHeader;
413
0
    seqHeader.requestId = mc->requestId;
414
0
    seqHeader.sequenceNumber = UA_SecureChannel_nextSequenceNumber(channel);
415
416
0
    UA_StatusCode res = UA_STATUSCODE_GOOD;
417
0
    res |= UA_encodeBinaryInternal(&header, &UA_TRANSPORT[UA_TRANSPORT_TCPMESSAGEHEADER],
418
0
                                   &header_pos, &mc->buf_end, NULL, NULL, NULL);
419
0
    res |= UA_UInt32_encodeBinary(&channel->securityToken.channelId,
420
0
                                  &header_pos, mc->buf_end);
421
0
    res |= UA_UInt32_encodeBinary(&channel->securityToken.tokenId,
422
0
                                  &header_pos, mc->buf_end);
423
0
    res |= UA_encodeBinaryInternal(&seqHeader, &UA_TRANSPORT[UA_TRANSPORT_SEQUENCEHEADER],
424
0
                                   &header_pos, &mc->buf_end, NULL, NULL, NULL);
425
0
    return res;
426
0
}
427
428
static UA_StatusCode
429
0
sendSymmetricChunk(UA_MessageContext *mc) {
430
0
    UA_SecureChannel *channel = mc->channel;
431
0
    const UA_SecurityPolicy *sp = channel->securityPolicy;
432
0
    UA_ConnectionManager *cm = channel->connectionManager;
433
0
    if(!UA_SecureChannel_isConnected(channel))
434
0
        return UA_STATUSCODE_BADCONNECTIONCLOSED;
435
436
    /* The size of the message payload */
437
0
    size_t bodyLength = (uintptr_t)mc->buf_pos -
438
0
        (uintptr_t)&mc->messageBuffer.data[UA_SECURECHANNEL_SYMMETRIC_HEADER_TOTALLENGTH];
439
440
    /* Early-declare variables so we can use a goto in the error case */
441
0
    size_t total_length = 0;
442
0
    size_t pre_sig_length = 0;
443
444
    /* Check if chunk exceeds the limits for the overall message */
445
0
    UA_StatusCode res = adjustCheckMessageLimitsSym(mc, bodyLength);
446
0
    UA_CHECK_STATUS(res, goto error);
447
448
0
    UA_LOG_TRACE_CHANNEL(sp->logger, channel,
449
0
                         "Send from a symmetric message buffer of length %lu "
450
0
                         "a message of header+payload length of %lu",
451
0
                         (long unsigned int)mc->messageBuffer.length,
452
0
                         (long unsigned int)
453
0
                         ((uintptr_t)mc->buf_pos - (uintptr_t)mc->messageBuffer.data));
454
455
    /* Add padding if the message is encrypted (not for AEAD policies) */
456
0
    if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT &&
457
0
       !UA_SecurityPolicy_isAead(sp))
458
0
        padChunk(channel, &sp->symSignatureAlgorithm, &sp->symEncryptionAlgorithm,
459
0
                 &mc->messageBuffer.data[UA_SECURECHANNEL_SYMMETRIC_HEADER_UNENCRYPTEDLENGTH],
460
0
                 &mc->buf_pos);
461
462
    /* Compute the total message length */
463
0
    pre_sig_length = (uintptr_t)mc->buf_pos - (uintptr_t)mc->messageBuffer.data;
464
0
    total_length = pre_sig_length;
465
0
    if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
466
0
       channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
467
0
        total_length += sp->symSignatureAlgorithm.
468
0
            getLocalSignatureSize(sp, channel->channelContext);
469
470
0
    UA_LOG_TRACE_CHANNEL(sp->logger, channel,
471
0
                         "Send from a symmetric message buffer of length %lu "
472
0
                         "a message of length %lu",
473
0
                         (long unsigned int)mc->messageBuffer.length,
474
0
                         (long unsigned int)total_length);
475
476
    /* Space for the padding and the signature have been reserved in setBufPos() */
477
0
    UA_assert(total_length <= channel->config.sendBufferSize);
478
479
    /* Adjust the buffer size of the network layer */
480
0
    mc->messageBuffer.length = total_length;
481
482
    /* Generate and encode the header for symmetric messages */
483
0
    res = encodeHeadersSym(mc, total_length);
484
0
    UA_CHECK_STATUS(res, goto error);
485
486
    /* Sign and encrypt the messge */
487
0
    res = signAndEncryptSym(mc, pre_sig_length, total_length);
488
0
    UA_CHECK_STATUS(res, goto error);
489
490
    /* Send the chunk. The buffer is freed in the network layer. If sending goes
491
     * wrong, the connection is removed in the next iteration of the
492
     * SecureChannel. Set the SecureChannel to closing already. */
493
0
    res = cm->sendWithConnection(cm, channel->connectionId,
494
0
                                 &UA_KEYVALUEMAP_NULL, &mc->messageBuffer);
495
0
    if(res != UA_STATUSCODE_GOOD && UA_SecureChannel_isConnected(channel))
496
0
        channel->state = UA_SECURECHANNELSTATE_CLOSING;
497
0
    return res;
498
499
0
 error:
500
    /* Free the unused message buffer */
501
0
    cm->freeNetworkBuffer(cm, channel->connectionId, &mc->messageBuffer);
502
0
    return res;
503
0
}
504
505
/* Callback from the encoding layer. Send the chunk and replace the buffer. */
506
static UA_StatusCode
507
sendSymmetricEncodingCallback(void *data, UA_Byte **buf_pos,
508
0
                              const UA_Byte **buf_end) {
509
    /* Set buf values from encoding in the messagecontext */
510
0
    UA_MessageContext *mc = (UA_MessageContext *)data;
511
0
    mc->buf_pos = *buf_pos;
512
0
    mc->buf_end = *buf_end;
513
514
    /* Send out */
515
0
    UA_StatusCode res = sendSymmetricChunk(mc);
516
0
    UA_CHECK_STATUS(res, return res);
517
518
    /* Set a new buffer for the next chunk */
519
0
    UA_ConnectionManager *cm = mc->channel->connectionManager;
520
0
    if(!UA_SecureChannel_isConnected(mc->channel))
521
0
        return UA_STATUSCODE_BADCONNECTIONCLOSED;
522
523
0
    res = cm->allocNetworkBuffer(cm, mc->channel->connectionId,
524
0
                                 &mc->messageBuffer,
525
0
                                 mc->channel->config.sendBufferSize);
526
0
    UA_CHECK_STATUS(res, return res);
527
528
    /* Hide bytes for header, padding and signature */
529
0
    setBufPos(mc);
530
0
    *buf_pos = mc->buf_pos;
531
0
    *buf_end = mc->buf_end;
532
0
    return UA_STATUSCODE_GOOD;
533
0
}
534
535
UA_StatusCode
536
UA_MessageContext_begin(UA_MessageContext *mc, UA_SecureChannel *channel,
537
0
                        UA_UInt32 requestId, UA_MessageType messageType) {
538
0
    UA_CHECK(messageType == UA_MESSAGETYPE_MSG || messageType == UA_MESSAGETYPE_CLO,
539
0
             return UA_STATUSCODE_BADINTERNALERROR);
540
541
0
    UA_ConnectionManager *cm = channel->connectionManager;
542
0
    if(!UA_SecureChannel_isConnected(channel))
543
0
        return UA_STATUSCODE_BADCONNECTIONCLOSED;
544
545
    /* Create the chunking info structure */
546
0
    mc->channel = channel;
547
0
    mc->requestId = requestId;
548
0
    mc->chunksSoFar = 0;
549
0
    mc->messageSizeSoFar = 0;
550
0
    mc->final = false;
551
0
    mc->messageBuffer = UA_BYTESTRING_NULL;
552
0
    mc->messageType = messageType;
553
554
    /* Allocate the message buffer */
555
0
    UA_StatusCode res =
556
0
        cm->allocNetworkBuffer(cm, channel->connectionId,
557
0
                               &mc->messageBuffer,
558
0
                               channel->config.sendBufferSize);
559
0
    UA_CHECK_STATUS(res, return res);
560
561
    /* Hide bytes for header, padding and signature */
562
0
    setBufPos(mc);
563
0
    return UA_STATUSCODE_GOOD;
564
0
}
565
566
UA_StatusCode
567
UA_MessageContext_encode(UA_MessageContext *mc, const void *content,
568
0
                         const UA_DataType *contentType) {
569
0
    UA_EncodeBinaryOptions encOpts;
570
0
    memset(&encOpts, 0, sizeof(UA_EncodeBinaryOptions));
571
0
    encOpts.namespaceMapping = mc->channel->namespaceMapping;
572
0
    UA_StatusCode res =
573
0
        UA_encodeBinaryInternal(content, contentType, &mc->buf_pos, &mc->buf_end,
574
0
                                &encOpts, sendSymmetricEncodingCallback, mc);
575
0
    if(res != UA_STATUSCODE_GOOD && mc->messageBuffer.length > 0)
576
0
        UA_MessageContext_abort(mc);
577
0
    return res;
578
0
}
579
580
UA_StatusCode
581
0
UA_MessageContext_finish(UA_MessageContext *mc) {
582
0
    mc->final = true;
583
0
    return sendSymmetricChunk(mc);
584
0
}
585
586
void
587
0
UA_MessageContext_abort(UA_MessageContext *mc) {
588
0
    UA_ConnectionManager *cm = mc->channel->connectionManager;
589
0
    if(!UA_SecureChannel_isConnected(mc->channel))
590
0
        return;
591
0
    cm->freeNetworkBuffer(cm, mc->channel->connectionId, &mc->messageBuffer);
592
0
}
593
594
/* Send a MSG or CLO message using symmetric encryption */
595
static UA_StatusCode
596
sendSymmetric(UA_SecureChannel *channel, UA_UInt32 requestId,
597
              UA_MessageType messageType, void *payload,
598
0
              const UA_DataType *payloadType) {
599
0
    if(!channel || !payload || !payloadType)
600
0
        return UA_STATUSCODE_BADINTERNALERROR;
601
602
0
    if(channel->state != UA_SECURECHANNELSTATE_OPEN)
603
0
        return UA_STATUSCODE_BADCONNECTIONCLOSED;
604
605
0
    UA_MessageContext mc;
606
0
    UA_StatusCode res = UA_MessageContext_begin(&mc, channel, requestId, messageType);
607
0
    UA_CHECK_STATUS(res, return res);
608
609
    /* Assert's required for clang-analyzer */
610
0
    UA_assert(mc.buf_pos ==
611
0
              &mc.messageBuffer.data[UA_SECURECHANNEL_SYMMETRIC_HEADER_TOTALLENGTH]);
612
0
    UA_assert(mc.buf_end <= &mc.messageBuffer.data[mc.messageBuffer.length]);
613
614
0
    res = UA_MessageContext_encode(&mc, &payloadType->binaryEncodingId,
615
0
                                   &UA_TYPES[UA_TYPES_NODEID]);
616
0
    UA_CHECK_STATUS(res, return res);
617
618
0
    res = UA_MessageContext_encode(&mc, payload, payloadType);
619
0
    UA_CHECK_STATUS(res, return res);
620
621
0
    return UA_MessageContext_finish(&mc);
622
0
}
623
624
UA_StatusCode
625
UA_SecureChannel_sendMSG(UA_SecureChannel *channel, UA_UInt32 requestId,
626
0
                         void *payload, const UA_DataType *payloadType) {
627
0
    return sendSymmetric(channel, requestId, UA_MESSAGETYPE_MSG,
628
0
                         payload, payloadType);
629
0
}
630
631
UA_StatusCode
632
UA_SecureChannel_sendCLO(UA_SecureChannel *channel, UA_UInt32 requestId,
633
0
                         UA_CloseSecureChannelRequest *req) {
634
0
    return sendSymmetric(channel, requestId, UA_MESSAGETYPE_CLO, req,
635
0
                         &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST]);
636
0
}
637
638
/********************************/
639
/* Receive and Process Messages */
640
/********************************/
641
642
/* Does the sequence number match? Otherwise try to rollover. See Part 6,
643
 * Section 6.7.2.4 of the standard. */
644
0
#define UA_SEQUENCENUMBER_ROLLOVER 4294966271
645
646
UA_UInt32
647
0
UA_SecureChannel_nextSequenceNumber(UA_SecureChannel *channel) {
648
    /* channel->sendSequenceNumber mirrors the reference-stack counter: a
649
     * pre-increment value initialized to 0. The legacy scheme emits the
650
     * counter (first = 1); the non-legacy scheme emits counter-1 (first = 0). */
651
0
    UA_UInt64 next = (UA_UInt64)channel->sendSequenceNumber + 1;
652
0
    if(channel->legacySequenceNumbers) {
653
        /* Legacy rollover: the first number after the max is 1. */
654
0
        if(next > UA_SEQUENCENUMBER_ROLLOVER)
655
0
            next = 1;
656
0
        channel->sendSequenceNumber = (UA_UInt32)next;
657
0
        return channel->sendSequenceNumber;
658
0
    }
659
    /* Non-legacy: the counter wraps to 0 after UA_UINT32_MAX so the emitted
660
     * value (counter - 1) covers the full UInt32 range and then restarts at 0. */
661
0
    if(next > UA_UINT32_MAX)
662
0
        next = 0;
663
0
    channel->sendSequenceNumber = (UA_UInt32)next;
664
0
    return (channel->sendSequenceNumber == 0) ?
665
0
        UA_UINT32_MAX : (channel->sendSequenceNumber - 1);
666
0
}
667
668
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
669
static UA_StatusCode
670
processSequenceNumberSym(UA_SecureChannel *channel, UA_UInt32 sequenceNumber) {
671
    if(sequenceNumber != channel->receiveSequenceNumber + 1) {
672
        /* The non-legacy (ECC) rollover from UA_UINT32_MAX to 0 is already
673
         * accepted by the check above (unsigned overflow makes
674
         * receiveSequenceNumber + 1 == 0). Only the legacy "< 1024" rollover
675
         * needs the special case below; non-legacy policies reject anything
676
         * that is not the immediate successor. */
677
        if(!channel->legacySequenceNumbers ||
678
           channel->receiveSequenceNumber + 1 <= UA_SEQUENCENUMBER_ROLLOVER ||
679
           sequenceNumber >= 1024)
680
            return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
681
        channel->receiveSequenceNumber = sequenceNumber - 1; /* Roll over */
682
    }
683
    ++channel->receiveSequenceNumber;
684
    return UA_STATUSCODE_GOOD;
685
}
686
#endif
687
688
static UA_StatusCode
689
0
unpackPayloadOPN(UA_SecureChannel *channel, UA_Chunk *chunk) {
690
0
    UA_assert(chunk->bytes.length >= UA_SECURECHANNEL_MESSAGE_MIN_LENGTH);
691
0
    size_t offset = UA_SECURECHANNEL_MESSAGEHEADER_LENGTH; /* Skip the message header */
692
0
    UA_UInt32 secureChannelId;
693
0
    UA_StatusCode res = UA_UInt32_decodeBinary(&chunk->bytes, &offset, &secureChannelId);
694
0
    UA_assert(res == UA_STATUSCODE_GOOD);
695
696
0
    UA_AsymmetricAlgorithmSecurityHeader asymHeader;
697
0
    res = UA_decodeBinaryInternal(&chunk->bytes, &offset, &asymHeader,
698
0
             &UA_TRANSPORT[UA_TRANSPORT_ASYMMETRICALGORITHMSECURITYHEADER], NULL);
699
0
    UA_CHECK_STATUS(res, return res);
700
701
    /* Declare before the first goto to avoid crosses-initialization in C++ */
702
0
    UA_SecurityPolicy *sp = NULL;
703
704
    /* Client/Server-specific processing. Creates a SecurityPolicy context and
705
     * attaches it to the channel. For the client, the remote certificate has
706
     * been verified before connecting. For the server the remote certificate is
707
     * verified within processOPNHeader. */
708
0
    UA_assert(channel->processOPNHeader);
709
0
    res = channel->processOPNHeader(channel->processOPNHeaderApplication,
710
0
                                    channel, &asymHeader);
711
0
    UA_CHECK_STATUS(res, goto error);
712
713
    /* On the client side, take the SecureChannelId from the first response */
714
0
    if(secureChannelId != 0 && channel->securityToken.channelId == 0)
715
0
        channel->securityToken.channelId = secureChannelId;
716
717
    /* Check the ChannelId */
718
#if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
719
    if(secureChannelId != channel->securityToken.channelId) {
720
        /* Allow the channel id to be different if the sent channel id is zero
721
         * and the SecurityToken is not initialized. This only happens on the
722
         * server side before we had a chance to tell the client which ChannelId
723
         * to use. */
724
        if(secureChannelId != 0 || channel->securityToken.tokenId != 0) {
725
            res = UA_STATUSCODE_BADSECURECHANNELIDINVALID;
726
            goto error;
727
        }
728
    }
729
#endif
730
731
    /* Generic header checking (for both client and server). Requires the
732
     * channel's SecurityPolicy. */
733
0
    res = checkAsymHeader(channel, &asymHeader);
734
0
    UA_CHECK_STATUS(res, goto error);
735
736
0
    UA_AsymmetricAlgorithmSecurityHeader_clear(&asymHeader);
737
738
    /* Decrypt the chunk payload */
739
0
    sp = channel->securityPolicy;
740
0
    res = decryptAndVerifyChunk(channel, &sp->asymSignatureAlgorithm,
741
0
                                &sp->asymEncryptionAlgorithm,
742
0
                                chunk->messageType, &chunk->bytes, offset);
743
0
    UA_CHECK_STATUS(res, return res);
744
745
    /* Decode the SequenceHeader */
746
0
    UA_SequenceHeader sequenceHeader;
747
0
    res = UA_decodeBinaryInternal(&chunk->bytes, &offset, &sequenceHeader,
748
0
                                  &UA_TRANSPORT[UA_TRANSPORT_SEQUENCEHEADER], NULL);
749
0
    UA_CHECK_STATUS(res, return res);
750
751
    /* Only the initial OPN establishes the receive sequence. Renewals remain
752
     * part of the existing channel's monotonically increasing sequence. */
753
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
754
    if(channel->state == UA_SECURECHANNELSTATE_OPEN) {
755
        res = processSequenceNumberSym(channel, sequenceHeader.sequenceNumber);
756
        UA_CHECK_STATUS(res, return res);
757
    } else
758
#endif
759
0
    {
760
0
        channel->receiveSequenceNumber = sequenceHeader.sequenceNumber;
761
0
    }
762
0
    chunk->requestId = sequenceHeader.requestId; /* Set the RequestId of the chunk */
763
764
    /* Use only the payload */
765
0
    chunk->bytes.data += offset;
766
0
    chunk->bytes.length -= offset;
767
0
    return UA_STATUSCODE_GOOD;
768
769
0
error:
770
0
    UA_AsymmetricAlgorithmSecurityHeader_clear(&asymHeader);
771
0
    return res;
772
0
}
773
774
static UA_StatusCode
775
unpackPayloadMSG(UA_SecureChannel *channel, UA_Chunk *chunk,
776
0
                 UA_DateTime nowMonotonic) {
777
0
    UA_CHECK_MEM(channel->securityPolicy, return UA_STATUSCODE_BADINTERNALERROR);
778
779
0
    UA_assert(chunk->bytes.length >= UA_SECURECHANNEL_MESSAGE_MIN_LENGTH);
780
0
    size_t offset = UA_SECURECHANNEL_MESSAGEHEADER_LENGTH; /* Skip the message header */
781
0
    UA_UInt32 secureChannelId;
782
0
    UA_UInt32 tokenId; /* SymmetricAlgorithmSecurityHeader */
783
0
    UA_StatusCode res = UA_STATUSCODE_GOOD;
784
0
    res |= UA_UInt32_decodeBinary(&chunk->bytes, &offset, &secureChannelId);
785
0
    res |= UA_UInt32_decodeBinary(&chunk->bytes, &offset, &tokenId);
786
0
    UA_assert(offset == UA_SECURECHANNEL_MESSAGE_MIN_LENGTH);
787
0
    UA_assert(res == UA_STATUSCODE_GOOD);
788
789
#if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
790
    /* Check the ChannelId. Non-opened channels have the id zero. */
791
    if(secureChannelId != channel->securityToken.channelId)
792
        return UA_STATUSCODE_BADSECURECHANNELIDINVALID;
793
#endif
794
795
    /* Check (and revolve) the SecurityToken */
796
0
    res = checkSymHeader(channel, tokenId, nowMonotonic);
797
0
    UA_CHECK_STATUS(res, return res);
798
799
    /* Decrypt the chunk payload */
800
0
    UA_SecurityPolicy *sp = channel->securityPolicy;
801
0
    res = decryptAndVerifyChunk(channel, &sp->symSignatureAlgorithm,
802
0
                                &sp->symEncryptionAlgorithm,
803
0
                                chunk->messageType, &chunk->bytes, offset);
804
0
    UA_CHECK_STATUS(res, return res);
805
806
    /* Check the sequence number. Skip sequence number checking for fuzzer to
807
     * improve coverage */
808
0
    UA_SequenceHeader sequenceHeader;
809
0
    res = UA_decodeBinaryInternal(&chunk->bytes, &offset, &sequenceHeader,
810
0
                                  &UA_TRANSPORT[UA_TRANSPORT_SEQUENCEHEADER], NULL);
811
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
812
    res |= processSequenceNumberSym(channel, sequenceHeader.sequenceNumber);
813
#endif
814
0
    UA_CHECK_STATUS(res, return res);
815
816
0
    chunk->requestId = sequenceHeader.requestId; /* Set the RequestId of the chunk */
817
818
    /* Use only the payload */
819
0
    chunk->bytes.data += offset;
820
0
    chunk->bytes.length -= offset;
821
0
    return UA_STATUSCODE_GOOD;
822
0
}
823
824
static UA_StatusCode
825
extractCompleteChunk(UA_SecureChannel *channel, UA_Chunk *chunk,
826
2.86k
                     UA_DateTime nowMonotonic) {
827
    /* At least 8 byte needed for the header */
828
2.86k
    size_t offset = channel->unprocessedOffset;
829
2.86k
    size_t remaining = channel->unprocessed.length - offset;
830
2.86k
    if(remaining < UA_SECURECHANNEL_MESSAGEHEADER_LENGTH)
831
586
        return UA_STATUSCODE_GOOD;
832
833
    /* Decoding the header cannot fail */
834
2.27k
    UA_TcpMessageHeader hdr;
835
2.27k
    UA_StatusCode res =
836
2.27k
        UA_decodeBinaryInternal(&channel->unprocessed, &offset, &hdr,
837
2.27k
                                &UA_TRANSPORT[UA_TRANSPORT_TCPMESSAGEHEADER], NULL);
838
2.27k
    UA_assert(res == UA_STATUSCODE_GOOD);
839
2.27k
    (void)res; /* pacify compilers if assert is ignored */
840
2.27k
    UA_MessageType msgType = (UA_MessageType)
841
2.27k
        (hdr.messageTypeAndChunkType & UA_BITMASK_MESSAGETYPE);
842
2.27k
    UA_ChunkType chunkType = (UA_ChunkType)
843
2.27k
        (hdr.messageTypeAndChunkType & UA_BITMASK_CHUNKTYPE);
844
845
    /* The message size is not allowed */
846
2.27k
    if(hdr.messageSize < UA_SECURECHANNEL_MESSAGE_MIN_LENGTH)
847
33
        return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
848
2.24k
    if(hdr.messageSize > channel->config.recvBufferSize)
849
289
        return UA_STATUSCODE_BADTCPMESSAGETOOLARGE;
850
851
    /* Incomplete chunk. Continue processing later. */
852
1.95k
    if(hdr.messageSize > remaining)
853
39
        return UA_STATUSCODE_GOOD;
854
855
    /* Set the chunk information */
856
1.91k
    chunk->bytes.data = channel->unprocessed.data + channel->unprocessedOffset;
857
1.91k
    chunk->bytes.length = hdr.messageSize;
858
1.91k
    chunk->messageType = msgType;
859
1.91k
    chunk->chunkType = chunkType;
860
1.91k
    chunk->requestId = 0;
861
1.91k
    chunk->copied = false;
862
863
    /* Increase the unprocessed offset */
864
1.91k
    channel->unprocessedOffset += hdr.messageSize;
865
866
    /* Validate, decrypt and unpack the chunk payload */
867
1.91k
    switch(msgType) {
868
13
    case UA_MESSAGETYPE_OPN:
869
13
        if(chunkType != UA_CHUNKTYPE_FINAL)
870
8
            return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
871
5
        if(channel->state != UA_SECURECHANNELSTATE_OPEN &&
872
5
           channel->state != UA_SECURECHANNELSTATE_OPN_SENT &&
873
5
           channel->state != UA_SECURECHANNELSTATE_ACK_SENT)
874
5
            return UA_STATUSCODE_BADINVALIDSTATE;
875
0
        res = unpackPayloadOPN(channel, chunk);
876
0
        break;
877
878
125
    case UA_MESSAGETYPE_MSG:
879
177
    case UA_MESSAGETYPE_CLO:
880
177
        if(chunkType != UA_CHUNKTYPE_FINAL &&
881
22
           chunkType != UA_CHUNKTYPE_INTERMEDIATE &&
882
20
           chunkType != UA_CHUNKTYPE_ABORT)
883
18
            return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
884
159
        if(channel->state != UA_SECURECHANNELSTATE_OPEN)
885
159
            return UA_STATUSCODE_BADINVALIDSTATE;
886
0
        res = unpackPayloadMSG(channel, chunk, nowMonotonic);
887
0
        break;
888
889
1
    case UA_MESSAGETYPE_RHE:
890
1.27k
    case UA_MESSAGETYPE_HEL:
891
1.28k
    case UA_MESSAGETYPE_ACK:
892
1.28k
    case UA_MESSAGETYPE_ERR:
893
1.28k
        if(chunkType != UA_CHUNKTYPE_FINAL)
894
15
            return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
895
        /* Hide the message header */
896
1.27k
        chunk->bytes.data += UA_SECURECHANNEL_MESSAGEHEADER_LENGTH;
897
1.27k
        chunk->bytes.length -= UA_SECURECHANNEL_MESSAGEHEADER_LENGTH;
898
1.27k
        break;
899
900
435
    default:
901
435
        res = UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
902
435
        break;
903
1.91k
    }
904
1.70k
    return res;
905
1.91k
}
906
907
UA_StatusCode
908
2.76k
UA_SecureChannel_loadBuffer(UA_SecureChannel *channel, const UA_ByteString buffer) {
909
    /* Append to the previous unprocessed buffer */
910
2.76k
    if(channel->unprocessed.length > 0) {
911
0
        UA_assert(channel->unprocessedCopied == true);
912
913
0
        UA_Byte *t = (UA_Byte*)
914
0
            UA_realloc(channel->unprocessed.data,
915
0
                       channel->unprocessed.length + buffer.length);
916
0
        if(!t)
917
0
            return UA_STATUSCODE_BADOUTOFMEMORY;
918
919
0
        if(buffer.length)
920
0
            memcpy(t + channel->unprocessed.length, buffer.data, buffer.length);
921
0
        channel->unprocessed.data = t;
922
0
        channel->unprocessed.length += buffer.length;
923
0
        return UA_STATUSCODE_GOOD;
924
0
    }
925
926
    /* Use the new buffer directly */
927
2.76k
    channel->unprocessed = buffer;
928
2.76k
    channel->unprocessedCopied = false;
929
2.76k
    return UA_STATUSCODE_GOOD;
930
2.76k
}
931
932
UA_StatusCode
933
UA_SecureChannel_getCompleteMessage(UA_SecureChannel *channel,
934
                                    UA_MessageType *messageType, UA_UInt32 *requestId,
935
                                    UA_ByteString *payload, UA_Boolean *copied,
936
2.86k
                                    UA_DateTime nowMonotonic) {
937
2.86k
    UA_Chunk chunk, *pchunk;
938
2.86k
    UA_StatusCode res = UA_STATUSCODE_GOOD;
939
940
2.86k
 extract_chunk:
941
    /* Extract+decode the next chunk from the buffer */
942
2.86k
    memset(&chunk, 0, sizeof(UA_Chunk));
943
2.86k
    res = extractCompleteChunk(channel, &chunk, nowMonotonic);
944
2.86k
    if(chunk.bytes.length == 0 || res != UA_STATUSCODE_GOOD)
945
1.58k
        return res; /* Error or no complete chunk could be extracted */
946
947
    /* Process the chunk */
948
1.27k
    switch(chunk.chunkType) {
949
0
    case UA_CHUNKTYPE_ABORT:
950
        /* Remove all chunks received so far. Then continue extracting chunks. */
951
0
        deleteChunks(channel);
952
0
        if(chunk.copied)
953
0
            UA_ByteString_clear(&chunk.bytes);
954
0
        goto extract_chunk;
955
956
0
    case UA_CHUNKTYPE_INTERMEDIATE:
957
        /* Validate the resource limits */
958
0
        if((channel->config.localMaxChunkCount != 0 &&
959
0
            channel->chunksCount >= channel->config.localMaxChunkCount) ||
960
0
           (channel->config.localMaxMessageSize != 0 &&
961
0
            channel->chunksLength + chunk.bytes.length > channel->config.localMaxMessageSize)) {
962
0
            if(chunk.copied)
963
0
                UA_ByteString_clear(&chunk.bytes);
964
0
            return UA_STATUSCODE_BADTCPMESSAGETOOLARGE;
965
0
        }
966
967
        /* Add the chunk to the queue. Then continue extracting more chunks. */
968
0
        pchunk = (UA_Chunk*)UA_malloc(sizeof(UA_Chunk));
969
0
        if(!pchunk) {
970
0
            if(chunk.copied)
971
0
                UA_ByteString_clear(&chunk.bytes);
972
0
            return UA_STATUSCODE_BADOUTOFMEMORY;
973
0
        }
974
0
        *pchunk = chunk;
975
0
        TAILQ_INSERT_TAIL(&channel->chunks, pchunk, pointers);
976
0
        channel->chunksCount++;
977
0
        channel->chunksLength += pchunk->bytes.length;
978
0
        goto extract_chunk;
979
980
1.27k
    case UA_CHUNKTYPE_FINAL:
981
1.27k
    default:
982
1.27k
        UA_assert(chunk.chunkType == UA_CHUNKTYPE_FINAL); /* Was checked before */
983
1.27k
        break; /* A final chunk was received -- assemble the message */
984
1.27k
    }
985
986
    /* Compute the message size */
987
1.27k
    size_t messageSize = chunk.bytes.length;
988
1.27k
    size_t messageChunks = 1; /* Include the final chunk */
989
1.27k
    UA_Chunk *first = NULL;
990
1.27k
    TAILQ_FOREACH(pchunk, &channel->chunks, pointers) {
991
0
        if(chunk.requestId != pchunk->requestId)
992
0
            continue;
993
0
        if(chunk.messageType != pchunk->messageType) {
994
0
            if(chunk.copied)
995
0
                UA_ByteString_clear(&chunk.bytes);
996
0
            return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
997
0
        }
998
0
        if(!first)
999
0
            first = pchunk;
1000
0
        messageChunks++;
1001
0
        messageSize += pchunk->bytes.length;
1002
0
    }
1003
1004
    /* Validate the assembled message limits. The final chunk also counts
1005
     * towards localMaxChunkCount. */
1006
1.27k
    if((channel->config.localMaxChunkCount != 0 &&
1007
1.27k
        messageChunks > channel->config.localMaxChunkCount) ||
1008
1.27k
       (channel->config.localMaxMessageSize != 0 &&
1009
1.27k
        messageSize > channel->config.localMaxMessageSize)) {
1010
0
        if(chunk.copied)
1011
0
            UA_ByteString_clear(&chunk.bytes);
1012
0
        return UA_STATUSCODE_BADTCPMESSAGETOOLARGE;
1013
0
    }
1014
1015
    /* Assemble the full payload and store it in chunk.bytes */
1016
1.27k
    if(messageSize > chunk.bytes.length) {
1017
0
        UA_assert(first != NULL);
1018
1019
        /* Allocate the full memory and initialize with the first chunk content.
1020
         * Use realloc to speed up. */
1021
0
        UA_ByteString message;
1022
0
        if(first->copied) {
1023
0
            message.data = (UA_Byte*)UA_realloc(first->bytes.data, messageSize);
1024
0
        } else {
1025
0
            message.data = (UA_Byte*)UA_malloc(messageSize);
1026
0
            if(message.data)
1027
0
                memcpy(message.data, first->bytes.data, first->bytes.length);
1028
0
        }
1029
0
        if(!message.data) {
1030
0
            if(chunk.copied)
1031
0
                UA_ByteString_clear(&chunk.bytes);
1032
0
            return UA_STATUSCODE_BADOUTOFMEMORY;
1033
0
        }
1034
0
        message.length = first->bytes.length;
1035
1036
        /* Remove the the first chunk */
1037
0
        pchunk = TAILQ_NEXT(first, pointers);
1038
0
        first->copied = false;
1039
0
        channel->chunksCount--;
1040
0
        channel->chunksLength -= first->bytes.length;
1041
0
        TAILQ_REMOVE(&channel->chunks, first, pointers);
1042
0
        UA_Chunk_delete(first);
1043
1044
        /* Copy over the content from the remaining intermediate chunks.
1045
         * And remove them right away. */
1046
0
        UA_Chunk *next;
1047
0
        for(; pchunk; pchunk = next) {
1048
0
            next = TAILQ_NEXT(pchunk, pointers);
1049
0
            if(chunk.requestId != pchunk->requestId)
1050
0
                continue;
1051
0
            memcpy(message.data + message.length, pchunk->bytes.data, pchunk->bytes.length);
1052
0
            message.length += pchunk->bytes.length;
1053
0
            channel->chunksCount--;
1054
0
            channel->chunksLength -= pchunk->bytes.length;
1055
0
            TAILQ_REMOVE(&channel->chunks, pchunk, pointers);
1056
0
            UA_Chunk_delete(pchunk);
1057
0
        }
1058
1059
        /* Copy over the content from the final chunk */
1060
0
        memcpy(message.data + message.length, chunk.bytes.data, chunk.bytes.length);
1061
0
        message.length += chunk.bytes.length;
1062
0
        UA_assert(message.length == messageSize);
1063
1064
        /* Set assembled message as the content of the final chunk */
1065
0
        if(chunk.copied)
1066
0
            UA_ByteString_clear(&chunk.bytes);
1067
0
        chunk.bytes = message;
1068
0
        chunk.copied = true;
1069
0
    }
1070
1071
    /* Return the assembled message */
1072
1.27k
    *requestId = chunk.requestId;
1073
1.27k
    *messageType = chunk.messageType;
1074
1.27k
    *payload = chunk.bytes;
1075
1.27k
    *copied = chunk.copied;
1076
1.27k
    return UA_STATUSCODE_GOOD;
1077
1.27k
}
1078
1079
UA_StatusCode
1080
2.76k
UA_SecureChannel_persistBuffer(UA_SecureChannel *channel) {
1081
2.76k
    UA_StatusCode res = UA_STATUSCODE_GOOD;
1082
1083
    /* Persist the chunks */
1084
2.76k
    UA_Chunk *chunk;
1085
2.76k
    TAILQ_FOREACH(chunk, &channel->chunks, pointers) {
1086
0
        if(chunk->copied)
1087
0
            continue;
1088
0
        UA_ByteString tmp = UA_BYTESTRING_NULL;
1089
0
        res |= UA_ByteString_copy(&chunk->bytes, &tmp);
1090
0
        chunk->bytes = tmp;
1091
0
        chunk->copied = true;
1092
0
    }
1093
1094
    /* No unprocessed bytes remaining */
1095
2.76k
    UA_assert(channel->unprocessed.length >= channel->unprocessedOffset);
1096
2.76k
    if(channel->unprocessed.length == channel->unprocessedOffset) {
1097
857
        if(channel->unprocessedCopied)
1098
0
            UA_ByteString_clear(&channel->unprocessed);
1099
857
        else
1100
857
            UA_ByteString_init(&channel->unprocessed);
1101
857
        channel->unprocessedOffset = 0;
1102
857
        return res;
1103
857
    }
1104
1105
    /* Allocate a new unprocessed ByteString.
1106
     * tmp is the empty string if malloc fails. */
1107
1.90k
    UA_ByteString tmp = UA_BYTESTRING_NULL;
1108
1.90k
    UA_ByteString remaining = channel->unprocessed;
1109
1.90k
    remaining.data += channel->unprocessedOffset;
1110
1.90k
    remaining.length -= channel->unprocessedOffset;
1111
1.90k
    res |= UA_ByteString_copy(&remaining, &tmp);
1112
1.90k
    if(channel->unprocessedCopied)
1113
0
        UA_ByteString_clear(&channel->unprocessed);
1114
1.90k
    channel->unprocessed = tmp;
1115
1.90k
    channel->unprocessedOffset = 0;
1116
    channel->unprocessedCopied = true;
1117
1.90k
    return res;
1118
2.76k
}