Coverage Report

Created: 2026-09-27 06:56

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/open62541/src/util/ua_encryptedsecret.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 2025 (c) Siemens AG (Author: Tin Raic)
6
 *    Copyright 2025-2026 (c) o6 Automation GmbH (Author: Julius Pfrommer)
7
 */
8
9
#include "ua_util_internal.h"
10
11
/************************/
12
/* ECC Encrypted Secret */
13
/************************/
14
15
typedef struct {
16
    /* Common Header */
17
    UA_NodeId typeId;
18
    UA_Byte encodingMask;
19
    UA_UInt32 length;
20
    UA_String securityPolicyUri;
21
    UA_ByteString certificate;
22
    UA_DateTime signingTime;
23
    UA_UInt16 keyDataLen;
24
25
    /* Policy Header*/
26
    UA_ByteString senderPublicKey;
27
    UA_ByteString receiverPublicKey;
28
29
    /* Payload */
30
    UA_ByteString nonce;
31
    UA_ByteString secret;
32
    /* UA_ByteString padding; // Computed when needed */
33
34
    /* Signature */
35
    UA_Byte* signature;
36
} UA_EccEncryptedSecretStruct;
37
38
static void
39
0
UA_EccEncryptedSecretStruct_init(UA_EccEncryptedSecretStruct* es) {
40
0
    memset(es, 0, sizeof(UA_EccEncryptedSecretStruct));
41
0
}
42
43
static void
44
0
UA_EccEncryptedSecretStruct_clear(UA_EccEncryptedSecretStruct* es) {
45
0
    UA_String_clear(&es->securityPolicyUri);
46
0
    UA_ByteString_clear(&es->certificate);
47
0
    UA_ByteString_clear(&es->senderPublicKey);
48
0
    UA_ByteString_clear(&es->receiverPublicKey);
49
0
    UA_ByteString_clear(&es->nonce);
50
0
    UA_ByteString_clear(&es->secret);
51
0
    UA_EccEncryptedSecretStruct_init(es);
52
0
}
53
54
static size_t
55
0
UA_EccEncryptedSecret_getCommonHeaderSize(const UA_EccEncryptedSecretStruct* src) {
56
0
    size_t len = 0;
57
0
    len += UA_calcSizeBinary(&src->typeId, &UA_TYPES[UA_TYPES_NODEID], NULL);
58
0
    len += UA_calcSizeBinary(&src->encodingMask, &UA_TYPES[UA_TYPES_BYTE], NULL);
59
0
    len += UA_calcSizeBinary(&src->length, &UA_TYPES[UA_TYPES_UINT32], NULL);
60
0
    len += UA_calcSizeBinary(&src->securityPolicyUri, &UA_TYPES[UA_TYPES_STRING], NULL);
61
0
    len += UA_calcSizeBinary(&src->certificate, &UA_TYPES[UA_TYPES_BYTESTRING], NULL);
62
0
    len += UA_calcSizeBinary(&src->signingTime, &UA_TYPES[UA_TYPES_DATETIME], NULL);
63
0
    len += UA_calcSizeBinary(&src->keyDataLen, &UA_TYPES[UA_TYPES_UINT16], NULL);
64
0
    return len;
65
0
}
66
67
static size_t
68
0
UA_EccEncryptedSecret_getPolicyHeaderSize(const UA_EccEncryptedSecretStruct* src) {
69
0
    size_t len = 0;
70
0
    len += UA_calcSizeBinary(&src->senderPublicKey, &UA_TYPES[UA_TYPES_BYTESTRING], NULL);
71
0
    len += UA_calcSizeBinary(&src->receiverPublicKey, &UA_TYPES[UA_TYPES_BYTESTRING], NULL);
72
0
    return len;
73
0
}
74
75
static UA_StatusCode
76
UA_EccEncryptedSecret_serializeCommonHeader(const UA_EccEncryptedSecretStruct *src,
77
0
                                            UA_Byte** bufPos, const UA_Byte* bufEnd) {
78
0
    UA_UInt32 length32 = (UA_UInt32)src->length;
79
0
    UA_StatusCode ret = UA_STATUSCODE_GOOD;
80
0
    ret |= UA_NodeId_encodeBinary(&src->typeId, bufPos, bufEnd);
81
0
    ret |= UA_Byte_encodeBinary(&src->encodingMask, bufPos, bufEnd);
82
0
    ret |= UA_UInt32_encodeBinary(&length32, bufPos, bufEnd);
83
0
    ret |= UA_String_encodeBinary(&src->securityPolicyUri, bufPos, bufEnd);
84
0
    ret |= UA_ByteString_encodeBinary(&src->certificate, bufPos, bufEnd);
85
0
    ret |= UA_DateTime_encodeBinary(&src->signingTime, bufPos, bufEnd);
86
0
    ret |= UA_UInt16_encodeBinary(&src->keyDataLen, bufPos, bufEnd);
87
0
    return ret;
88
0
}
89
90
static UA_StatusCode
91
UA_EccEncryptedSecret_serializePolicyHeader(const UA_EccEncryptedSecretStruct *src,
92
0
                                            UA_Byte** bufPos, const UA_Byte* bufEnd) {
93
0
    UA_StatusCode ret = UA_STATUSCODE_GOOD;
94
0
    ret |= UA_ByteString_encodeBinary(&src->senderPublicKey, bufPos, bufEnd);
95
0
    ret |= UA_ByteString_encodeBinary(&src->receiverPublicKey, bufPos, bufEnd);
96
0
    return ret;
97
0
}
98
99
static UA_StatusCode
100
UA_EccEncryptedSecret_deserializeCommonHeader(UA_EccEncryptedSecret *src,
101
                                              UA_EccEncryptedSecretStruct *dest,
102
0
                                              size_t* offset) {
103
0
    UA_StatusCode ret = UA_STATUSCODE_GOOD;
104
0
    ret |= UA_NodeId_decodeBinary(src, offset, &dest->typeId);
105
0
    ret |= UA_Byte_decodeBinary(src, offset, &dest->encodingMask);
106
0
    ret |= UA_UInt32_decodeBinary(src, offset, &dest->length);
107
0
    ret |= UA_String_decodeBinary(src, offset, &dest->securityPolicyUri);
108
0
    ret |= UA_ByteString_decodeBinary(src, offset, &dest->certificate);
109
0
    ret |= UA_DateTime_decodeBinary(src, offset, &dest->signingTime);
110
0
    ret |= UA_UInt16_decodeBinary(src, offset, &dest->keyDataLen);
111
0
    return ret;
112
0
}
113
114
static UA_StatusCode
115
UA_EccEncryptedSecret_deserializePolicyHeader(UA_EccEncryptedSecret *src,
116
                                              UA_EccEncryptedSecretStruct *dest,
117
0
                                              size_t* offset) {
118
0
    UA_StatusCode ret = UA_STATUSCODE_GOOD;
119
0
    ret |= UA_ByteString_decodeBinary(src, offset, &dest->senderPublicKey);
120
0
    ret |= UA_ByteString_decodeBinary(src, offset, &dest->receiverPublicKey);
121
0
    return ret;
122
0
}
123
124
UA_StatusCode
125
encryptUserIdentityTokenEcc(UA_Logger *logger, UA_SecureChannel *channel,
126
                            const UA_SecurityPolicy *sp, void *spContext,
127
                            UA_ByteString *tokenData,
128
                            const UA_ByteString serverSessionNonce,
129
0
                            const UA_ByteString serverEphemeralPubKey) {
130
    /* Extract some basic information from the SecurityPolicy. AEAD policies
131
     * (AES-GCM) expose a dedicated IV length (12 bytes) and append an
132
     * authentication tag after the ciphertext; legacy CBC policies use the
133
     * cipher block size as the IV length and have no tag. */
134
0
    UA_Boolean aead = UA_SecurityPolicy_isAead(sp);
135
0
    size_t symKeyLen = sp->symEncryptionAlgorithm.getLocalKeyLength(sp, spContext);
136
0
    size_t ivLen = (aead && sp->symEncryptionAlgorithm.getLocalIvLength) ?
137
0
        sp->symEncryptionAlgorithm.getLocalIvLength(sp, spContext) :
138
0
        sp->symEncryptionAlgorithm.getRemoteBlockSize(sp, spContext);
139
0
    size_t tagLen = aead ?
140
0
        sp->symSignatureAlgorithm.getLocalSignatureSize(sp, spContext) : 0;
141
0
    size_t sigLen = sp->asymSignatureAlgorithm.getRemoteSignatureSize(sp, spContext);
142
0
    UA_assert(symKeyLen > 0 && ivLen > 0);
143
144
    /* Filling out the EccEncryptedSecretStruct fields. The length field is
145
     * computed after. */
146
0
    UA_EccEncryptedSecretStruct secret;
147
0
    UA_EccEncryptedSecretStruct_init(&secret);
148
0
    secret.typeId = UA_NS0ID(ECCENCRYPTEDSECRET);
149
0
    secret.encodingMask = 0x01;
150
0
    secret.signingTime = UA_DateTime_now();
151
152
    /* Copy-only methods */
153
0
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
154
0
    retval |= UA_String_copy(&sp->policyUri, &secret.securityPolicyUri);
155
0
    retval |= UA_ByteString_copy(&sp->localCertificate, &secret.certificate);
156
0
    retval |= UA_ByteString_copy(&serverEphemeralPubKey, &secret.receiverPublicKey);
157
0
    retval |= UA_ByteString_copy(&serverSessionNonce, &secret.nonce);
158
0
    retval |= UA_ByteString_copy(tokenData, &secret.secret);
159
0
    if(retval != UA_STATUSCODE_GOOD) {
160
0
        UA_EccEncryptedSecretStruct_clear(&secret);
161
0
        return retval;
162
0
    }
163
164
    /* Generate a new local ephemeral key. The private part remains persisted
165
     * inside the SecurityPolicy. */
166
0
    size_t ephKeyLen = sp->nonceLength; /* Also length of the ephemeral public key */
167
0
    retval = UA_ByteString_allocBuffer(&secret.senderPublicKey, ephKeyLen);
168
0
    if(retval != UA_STATUSCODE_GOOD) {
169
0
        UA_EccEncryptedSecretStruct_clear(&secret);
170
0
        return retval;
171
0
    }
172
0
    secret.senderPublicKey.data[0] = 'e';
173
0
    secret.senderPublicKey.data[1] = 'p';
174
0
    secret.senderPublicKey.data[2] = 'h';
175
0
    retval = sp->generateNonce(sp, spContext, &secret.senderPublicKey);
176
0
    if(retval != UA_STATUSCODE_GOOD) {
177
0
        UA_LOG_ERROR_CHANNEL(logger, channel,
178
0
                     "EccEncryptedSecret: Failed to generate local ephemeral key");
179
0
        UA_EccEncryptedSecretStruct_clear(&secret);
180
0
        return retval;
181
0
    }
182
183
    /* Compute the padding. the alignment block is 16 bytes for AEAD (AES-GCM)
184
     * and the IV/block size for CBC. The padding region is `paddingCount` bytes
185
     * of value paddingCount, followed by a 2-byte padding-size field
186
     * (PaddingSize | ExtraPaddingSize); those 2 bytes are included in the
187
     * alignment. */
188
0
    size_t blockSize = aead ? 16 : ivLen;
189
0
    size_t baseLen = UA_ByteString_calcSizeBinary(&secret.nonce) +
190
0
                     UA_ByteString_calcSizeBinary(&secret.secret);
191
0
    size_t modLen = (baseLen + 2) % blockSize;
192
0
    size_t paddingCount = (modLen == 0) ? 0 : (blockSize - modLen);
193
0
    if(paddingCount + secret.secret.length < blockSize)
194
0
        paddingCount += blockSize;
195
0
    size_t encryptedLength = baseLen + paddingCount + 2;
196
197
    /* Compute the total length including the headers and the signature */
198
0
    size_t signatureLen = sp->asymSignatureAlgorithm.
199
0
        getLocalSignatureSize(sp, spContext);
200
0
    secret.keyDataLen = (UA_UInt16)
201
0
        UA_EccEncryptedSecret_getPolicyHeaderSize(&secret);
202
0
    size_t totalLength = encryptedLength + tagLen + secret.keyDataLen +
203
0
        UA_EccEncryptedSecret_getCommonHeaderSize(&secret) + signatureLen;
204
205
    /* The EncryptedSecret "Length" field is the number of bytes that FOLLOW the
206
     * Length field, not the full serialized size. Subtract the common-header
207
     * prefix (TypeId NodeId + EncodingByte + the Length field itself = 9
208
     * bytes). */
209
0
    size_t headerPrefix =
210
0
        UA_calcSizeBinary(&secret.typeId, &UA_TYPES[UA_TYPES_NODEID], NULL) +
211
0
        UA_calcSizeBinary(&secret.encodingMask, &UA_TYPES[UA_TYPES_BYTE], NULL) +
212
0
        UA_calcSizeBinary(&secret.length, &UA_TYPES[UA_TYPES_UINT32], NULL);
213
0
    secret.length = (UA_UInt32)(totalLength - headerPrefix);
214
215
    /* Compute the symmetric key to encrypt */
216
0
    UA_ByteString symEncKeyMaterial;
217
0
    retval = UA_ByteString_allocBuffer(&symEncKeyMaterial, symKeyLen+ivLen);
218
0
    if(retval != UA_STATUSCODE_GOOD) {
219
0
        UA_EccEncryptedSecretStruct_clear(&secret);
220
0
        return retval;
221
0
    }
222
223
    /* This is a (temporary) measure so that the salt generation function (for
224
     * the symmetric key derivation ) knows that the salt is generated for
225
     * session authentication (to choose the correct label) */
226
    /* TODO: find a better way to signal symmetric key generation for session
227
     * authentication */
228
0
    symEncKeyMaterial.data[0] = 0x03;
229
0
    symEncKeyMaterial.data[1] = 0x03;
230
0
    symEncKeyMaterial.data[2] = 0x04;
231
0
    retval = sp->generateKey(sp, spContext, &secret.receiverPublicKey,
232
0
                             &secret.senderPublicKey, &symEncKeyMaterial);
233
0
    if(retval != UA_STATUSCODE_GOOD) {
234
0
        UA_LOG_ERROR_CHANNEL(logger, channel,
235
0
                             "EccEncryptedSecret: Failed to derive key material");
236
0
        UA_ByteString_clear(&symEncKeyMaterial);
237
0
        UA_EccEncryptedSecretStruct_clear(&secret);
238
0
        return retval;
239
0
    }
240
241
    /* Extracting the key and the initialization vector from the key material */
242
0
    UA_ByteString encKey = {symKeyLen, symEncKeyMaterial.data};
243
0
    UA_ByteString iv = {ivLen, &symEncKeyMaterial.data[symKeyLen]};
244
0
    retval |= sp->setLocalSymEncryptingKey(sp, spContext, &encKey);
245
0
    retval |= sp->setLocalSymIv(sp, spContext, &iv);
246
0
    UA_ByteString_clear(&symEncKeyMaterial);
247
0
    if(retval != UA_STATUSCODE_GOOD) {
248
0
        UA_LOG_ERROR_CHANNEL(logger, channel,
249
0
                             "EccEncryptedSecret: Failed to set EncryptingKey/"
250
0
                             "IV in the SecurityPolicy");
251
0
        UA_EccEncryptedSecretStruct_clear(&secret);
252
0
        return retval;
253
0
    }
254
255
    /* Allocate the output buffer */
256
0
    UA_ByteString output;
257
0
    retval = UA_ByteString_allocBuffer(&output, totalLength);
258
0
    if(retval != UA_STATUSCODE_GOOD) {
259
0
        UA_EccEncryptedSecretStruct_clear(&secret);
260
0
        return retval;
261
0
    }
262
263
    /* Encode all the content into the output buffer */
264
0
    UA_Byte* bufPos = output.data;
265
0
    UA_Byte* bufEnd = output.data + output.length;
266
0
    retval |= UA_EccEncryptedSecret_serializeCommonHeader(&secret, &bufPos, bufEnd);
267
0
    retval |= UA_EccEncryptedSecret_serializePolicyHeader(&secret, &bufPos, bufEnd);
268
0
    UA_Byte* payloadPos = bufPos;
269
0
    retval |= UA_ByteString_encodeBinary(&secret.nonce, &bufPos, bufEnd);
270
0
    retval |= UA_ByteString_encodeBinary(&secret.secret, &bufPos, bufEnd);
271
0
    UA_Byte pad = (UA_Byte)(paddingCount & 0xFF);
272
0
    for(size_t i = 0; i < paddingCount; i++) {
273
0
        *bufPos = pad;
274
0
        bufPos++;
275
0
    }
276
    /* 2-byte padding-size field: PaddingSize byte + ExtraPaddingSize byte.
277
     * For paddingCount < 256 this equals the little-endian UInt16. */
278
0
    UA_UInt16 paddingCount16 = (UA_UInt16)paddingCount;
279
0
    retval |= UA_UInt16_encodeBinary(&paddingCount16, &bufPos, bufEnd);
280
0
    if(retval != UA_STATUSCODE_GOOD) {
281
0
        UA_EccEncryptedSecretStruct_clear(&secret);
282
0
        UA_ByteString_clear(&output);
283
0
        return retval;
284
0
    }
285
286
    /* Encrypt the payload region in-situ. For AEAD (AES-GCM) the GCM primitive
287
     * writes the authentication tag into the last `tagLen` bytes of the buffer
288
     * it is given, so the region passed in spans the plaintext plus the
289
     * reserved tag bytes. The AAD is the EccEncryptedSecret header preceding
290
     * the encrypted region, and the IV is used unmasked (tokenId / sequence
291
     * number = 0). */
292
0
    UA_ByteString payload = {(size_t)(bufPos - payloadPos) + tagLen, payloadPos};
293
0
    if(aead) {
294
0
        UA_ByteString aad = {(size_t)(payloadPos - output.data), output.data};
295
0
        retval |= sp->setMessageSecurityParameters(sp, spContext, 0, 0, &aad);
296
0
    }
297
0
    retval |= sp->symEncryptionAlgorithm.encrypt(sp, spContext, &payload);
298
0
    if(retval != UA_STATUSCODE_GOOD) {
299
0
        UA_LOG_ERROR_CHANNEL(logger, channel,
300
0
                     "EccEncryptedSecret: Failed to encrypt the payload");
301
0
        UA_EccEncryptedSecretStruct_clear(&secret);
302
0
        UA_ByteString_clear(&output);
303
0
        return retval;
304
0
    }
305
306
    /* The authentication tag (if any) now occupies the next tagLen bytes;
307
     * advance past it to the signature slot. */
308
0
    bufPos += tagLen;
309
0
    UA_assert(bufPos + sigLen == bufEnd);
310
311
    /* Compute the overall signature over everything except the signature. */
312
0
    UA_ByteString sigContent = {(size_t)(bufPos - output.data), output.data};
313
0
    UA_ByteString signature = {sigLen, bufPos};
314
0
    retval = sp->asymSignatureAlgorithm.sign(sp, spContext, &sigContent, &signature);
315
0
    if(retval != UA_STATUSCODE_GOOD) {
316
0
        UA_LOG_ERROR_CHANNEL(logger, channel,
317
0
                     "EccEncryptedSecret: Failed to sign the EccEncryptedSecret");
318
0
        UA_EccEncryptedSecretStruct_clear(&secret);
319
0
        UA_ByteString_clear(&output);
320
0
        return retval;
321
0
    }
322
323
    /* Replace tokenData with the output */
324
0
    UA_ByteString_clear(tokenData);
325
0
    *tokenData = output;
326
327
0
    UA_EccEncryptedSecretStruct_clear(&secret);
328
0
    return UA_STATUSCODE_GOOD;
329
0
}
330
331
UA_StatusCode
332
decryptUserTokenEcc(UA_Logger *logger, UA_SecureChannel *channel,
333
                    const UA_SecurityPolicy *sp, void *spContext,
334
                    UA_ByteString sessionServerNonce,
335
0
                    UA_EccEncryptedSecret *es) {
336
    /* ECC usage verified before calling into this function */
337
0
    UA_assert(UA_SecurityPolicy_isEcc(sp));
338
339
    /* Define and initialize in case of clean-up */
340
0
    UA_StatusCode res = UA_STATUSCODE_GOOD;
341
0
    UA_EccEncryptedSecretStruct esd;
342
0
    UA_EccEncryptedSecretStruct_init(&esd);
343
0
    UA_ByteString symEncKeyMaterial = UA_BYTESTRING_NULL;
344
0
    UA_ByteString pass = UA_BYTESTRING_NULL;
345
346
0
    size_t offset = 0;
347
0
    res = UA_EccEncryptedSecret_deserializeCommonHeader(es, &esd, &offset);
348
0
    if(res != UA_STATUSCODE_GOOD) {
349
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
350
0
                             "Failed to decode the common header");
351
0
        goto cleanecc;
352
0
    }
353
354
    /* Check TypeId */
355
0
    UA_NodeId eccTypeId = UA_NS0ID(ECCENCRYPTEDSECRET);
356
0
    if(!UA_NodeId_equal(&eccTypeId, &esd.typeId) ||
357
0
       esd.encodingMask != 0x01 ||
358
0
       !UA_String_equal(&esd.securityPolicyUri, &sp->policyUri)) {
359
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
360
0
                             "Inconsistent common header");
361
0
        res = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
362
0
        goto cleanecc;
363
0
    }
364
365
    /* The "Length" field counts the bytes following the Length field, so the
366
     * end of the secret is (Length + the common-header prefix: TypeId NodeId +
367
     * EncodingByte + Length field). Validate it and use it (instead of the
368
     * whole ByteString size) for the payload/signature bounds. */
369
0
    size_t headerPrefix =
370
0
        UA_calcSizeBinary(&esd.typeId, &UA_TYPES[UA_TYPES_NODEID], NULL) +
371
0
        UA_calcSizeBinary(&esd.encodingMask, &UA_TYPES[UA_TYPES_BYTE], NULL) +
372
0
        UA_calcSizeBinary(&esd.length, &UA_TYPES[UA_TYPES_UINT32], NULL);
373
0
    if(headerPrefix > es->length ||
374
0
       (size_t)esd.length > es->length - headerPrefix) {
375
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
376
0
                             "Inconsistent Length field");
377
0
        res = UA_STATUSCODE_BADDECODINGERROR;
378
0
        goto cleanecc;
379
0
    }
380
0
    size_t endOfSecret = headerPrefix + (size_t)esd.length;
381
0
    if(endOfSecret <= offset) {
382
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
383
0
                             "Inconsistent Length field");
384
0
        res = UA_STATUSCODE_BADDECODINGERROR;
385
0
        goto cleanecc;
386
0
    }
387
388
    /* Ensure that the signature and at least one payload byte fit before
389
     * subtracting the signature length from an attacker-controlled length. */
390
0
    size_t sigLen = sp->asymSignatureAlgorithm.getRemoteSignatureSize(sp, spContext);
391
0
    if(sigLen >= endOfSecret - offset) {
392
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
393
0
                             "Inconsistent payload / signature length");
394
0
        res = UA_STATUSCODE_BADIDENTITYTOKENINVALID;
395
0
        goto cleanecc;
396
0
    }
397
398
    /* Verify signature */
399
0
    size_t signedDataLen = endOfSecret - sigLen;
400
0
    UA_ByteString signedData = {signedDataLen, es->data};
401
0
    UA_ByteString signature = {sigLen, &es->data[signedDataLen]};
402
0
    res = sp->asymSignatureAlgorithm.verify(sp, spContext, &signedData, &signature);
403
0
    if(res != UA_STATUSCODE_GOOD) {
404
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
405
0
                             "Signature verification failed");
406
0
        goto cleanecc;
407
0
    }
408
409
0
    size_t oldoffset = offset;
410
0
    res = UA_EccEncryptedSecret_deserializePolicyHeader(es, &esd, &offset);
411
0
    if(res != UA_STATUSCODE_GOOD) {
412
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
413
0
                             "Failed to decode the policy header");
414
0
        goto cleanecc;
415
0
    }
416
417
    /* Sanity check of the key data length.
418
     * This needs to include the 2x4 byte length fields. */
419
0
    if(esd.keyDataLen != (UA_UInt16)(offset - oldoffset)) {
420
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
421
0
                             "Inconstent KeyDataLength");
422
0
        res = UA_STATUSCODE_BADIDENTITYTOKENINVALID;
423
0
        goto cleanecc;
424
0
    }
425
426
0
    UA_ByteString payload = {endOfSecret - offset - sigLen, es->data + offset};
427
428
    /* Deriving (remote) symmetric encryption key to decrypt the payload.
429
     * AEAD policies (AES-GCM) use a dedicated 12-byte IV length; legacy CBC
430
     * uses the cipher block size. */
431
0
    UA_Boolean aead = UA_SecurityPolicy_isAead(sp);
432
0
    size_t symKeyLen = sp->symEncryptionAlgorithm.getRemoteKeyLength(sp, spContext);
433
0
    size_t ivLen = (aead && sp->symEncryptionAlgorithm.getLocalIvLength) ?
434
0
        sp->symEncryptionAlgorithm.getLocalIvLength(sp, spContext) :
435
0
        sp->symEncryptionAlgorithm.getRemoteBlockSize(sp, spContext);
436
0
    res = UA_ByteString_allocBuffer(&symEncKeyMaterial, symKeyLen+ivLen);
437
0
    if(res != UA_STATUSCODE_GOOD)
438
0
        goto cleanecc;
439
440
    /* This is a (temporary) measure so that the salt generation function (for
441
     * the symmetric key derivation ) knows that the salt is generated for
442
     * session authentication (to choose the correct label) */
443
    /* TODO: find a better way to signal symmetric key generation for session
444
     * authentication */
445
0
    symEncKeyMaterial.data[0] = 0x03;
446
0
    symEncKeyMaterial.data[1] = 0x03;
447
0
    symEncKeyMaterial.data[2] = 0x04;
448
449
    /* Call logic for server for session authentication: receiver public key is
450
     * local (server), sender public key is remote (client) */
451
0
    res = sp->generateKey(sp, spContext, &esd.receiverPublicKey,
452
0
                          &esd.senderPublicKey, &symEncKeyMaterial);
453
0
    if(res != UA_STATUSCODE_GOOD) {
454
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
455
0
                             "Failed to derive key material");
456
0
        goto cleanecc;
457
0
    }
458
459
    /* Extract the encryption key and the initialization vector */
460
0
    UA_ByteString encKey = {symKeyLen, symEncKeyMaterial.data};
461
0
    UA_ByteString iv = {ivLen, &symEncKeyMaterial.data[symKeyLen]};
462
463
    /* Set IV and RemoteEncryptingKey. That is all we need to decode the
464
     * secret. */
465
0
    res |= sp->setRemoteSymEncryptingKey(sp, spContext, &encKey);
466
0
    res |= sp->setRemoteSymIv(sp, spContext, &iv);
467
0
    if(res != UA_STATUSCODE_GOOD) {
468
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
469
0
                             "Failed to set IV/RemoteSymEncryptingKey");
470
0
        goto cleanecc;
471
0
    }
472
473
    /* For AEAD (AES-GCM), the AAD is the EccEncryptedSecret header that
474
     * precedes the encrypted region and the IV is used unmasked (tokenId /
475
     * sequence number = 0). The 16-byte tag at the end of the payload is
476
     * verified (and stripped) by the decrypt. */
477
0
    if(aead) {
478
0
        UA_ByteString aad = {(size_t)(payload.data - es->data), es->data};
479
0
        res = sp->setMessageSecurityParameters(sp, spContext, 0, 0, &aad);
480
0
        if(res != UA_STATUSCODE_GOOD) {
481
0
            UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
482
0
                                 "Failed to set AEAD parameters");
483
0
            goto cleanecc;
484
0
        }
485
0
    }
486
487
    /* Decrypt payload (password) */
488
0
    res = sp->symEncryptionAlgorithm.decrypt(sp, spContext, &payload);
489
0
    if(res != UA_STATUSCODE_GOOD) {
490
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
491
0
                             "Failed to decrypt the payload");
492
0
        goto cleanecc;
493
0
    }
494
495
    /* Decode nonce and secret */
496
0
    offset = 0; /* Within the payload */
497
0
    UA_ByteString nonce;
498
0
    UA_StatusCode ret = UA_STATUSCODE_GOOD;
499
0
    ret |= UA_ByteString_decodeBinary(&payload, &offset, &nonce);
500
0
    ret |= UA_ByteString_decodeBinary(&payload, &offset, &pass);
501
0
    if(ret != UA_STATUSCODE_GOOD) {
502
0
        UA_ByteString_clear(&nonce);
503
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
504
0
                             "Failed to decode the payload");
505
0
        goto cleanecc;
506
0
    }
507
508
    /* Compare the nonce */
509
0
    UA_Boolean nonceMatch = UA_ByteString_equal(&sessionServerNonce, &nonce);
510
0
    UA_ByteString_clear(&nonce);
511
0
    if(!nonceMatch) {
512
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
513
0
                             "Nonce does not match");
514
0
        res = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
515
0
        goto cleanecc;
516
0
    }
517
518
    /* Decode the padding length and validate */
519
0
    UA_UInt16 paddingSize = 0;
520
0
    size_t paddingOffset = payload.length - 2;
521
0
    UA_UInt16_decodeBinary(&payload, &paddingOffset, &paddingSize);
522
0
    UA_Byte padd = (UA_Byte)paddingSize;
523
0
    for(; offset < payload.length-2; offset++) {
524
0
        if(payload.data[offset] != padd) {
525
0
            UA_LOG_ERROR_CHANNEL(logger, channel,
526
0
                                 "EccEncryptedSecret: Inconsistent padding");
527
0
            res = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
528
0
            goto cleanecc;
529
0
        }
530
0
    }
531
532
    /* Copy the password to the output */
533
0
    memcpy(es->data, pass.data, pass.length);
534
0
    es->length = pass.length;
535
536
0
cleanecc:
537
0
    UA_EccEncryptedSecretStruct_clear(&esd);
538
0
    UA_ByteString_clear(&symEncKeyMaterial);
539
0
    UA_ByteString_clear(&pass);
540
0
    return res;
541
0
}
542
543
/***************************/
544
/* Legacy Encrypted Secret */
545
/***************************/
546
547
UA_StatusCode
548
encryptSecretLegacy(const UA_SecurityPolicy *sp, void *spContext,
549
                    const UA_ByteString serverSessionNonce,
550
0
                    UA_ByteString *tokenData) {
551
    /* Compute the encrypted length (at least one byte padding) */
552
0
    size_t plainTextBlockSize = sp->asymEncryptionAlgorithm.
553
0
        getRemotePlainTextBlockSize(sp, spContext);
554
0
    size_t encryptedBlockSize = sp->asymEncryptionAlgorithm.
555
0
        getRemoteBlockSize(sp, spContext);
556
0
    UA_UInt32 length =
557
0
        (UA_UInt32)(tokenData->length + serverSessionNonce.length);
558
0
    UA_UInt32 totalLength = length + 4; /* Including the length field */
559
0
    size_t blocks = totalLength / plainTextBlockSize;
560
0
    if(totalLength % plainTextBlockSize != 0)
561
0
        blocks++;
562
0
    size_t encryptedLength = blocks * encryptedBlockSize;
563
564
    /* Allocate memory for the encrypted secret */
565
0
    UA_ByteString encrypted;
566
0
    UA_StatusCode res = UA_ByteString_allocBuffer(&encrypted, encryptedLength);
567
0
    if(res != UA_STATUSCODE_GOOD)
568
0
        return res;
569
570
    /* Copy the secret and the nonce into the output */
571
0
    UA_Byte *pos = encrypted.data;
572
0
    const UA_Byte *end = &encrypted.data[encrypted.length];
573
0
    res = UA_UInt32_encodeBinary(&length, &pos, end);
574
0
    memcpy(pos, tokenData->data, tokenData->length);
575
0
    memcpy(&pos[tokenData->length], serverSessionNonce.data,
576
0
           serverSessionNonce.length);
577
0
    UA_assert(res == UA_STATUSCODE_GOOD);
578
579
    /* Add padding
580
     *
581
     * 7.36.2.2 Legacy Encrypted Token Secret Format: A Client should not add
582
     * any padding after the secret. If a Client adds padding then all bytes
583
     * shall be zero. A Server shall check for padding added by Clients and
584
     * ensure that all padding bytes are zeros. */
585
0
    size_t paddedLength = plainTextBlockSize * blocks;
586
0
    for(size_t i = totalLength; i < paddedLength; i++)
587
0
        encrypted.data[i] = 0;
588
0
    encrypted.length = paddedLength;
589
590
    /* Encrypt */
591
0
    res = sp->asymEncryptionAlgorithm.encrypt(sp, spContext, &encrypted);
592
0
    if(res != UA_STATUSCODE_GOOD) {
593
0
        UA_ByteString_clear(&encrypted);
594
0
        return res;
595
0
    }
596
597
    /* Replace the tokenData with the output */
598
0
    encrypted.length = encryptedLength;
599
0
    UA_ByteString_clear(tokenData);
600
0
    *tokenData = encrypted;
601
0
    return UA_STATUSCODE_GOOD;
602
0
}
603
604
UA_StatusCode
605
decryptSecretLegacy(const UA_SecurityPolicy *sp, void *spContext,
606
                    const UA_ByteString serverSessionNonce,
607
0
                    UA_ByteString *tokenData) {
608
0
    UA_UInt32 secretLen = 0;
609
0
    UA_ByteString secret, tokenNonce;
610
0
    size_t tokenpos = 0;
611
0
    size_t offset = 0;
612
0
    const UA_SecurityPolicyEncryptionAlgorithm *asymEnc = &sp->asymEncryptionAlgorithm;
613
614
    /* Decrypt the secret */
615
0
    UA_StatusCode res = UA_STATUSCODE_BADIDENTITYTOKENINVALID;
616
0
    if(UA_ByteString_copy(tokenData, &secret) != UA_STATUSCODE_GOOD ||
617
0
       asymEnc->decrypt(sp, spContext, &secret) != UA_STATUSCODE_GOOD)
618
0
        goto cleanup;
619
620
    /* The secret starts with a UInt32 length for the content */
621
0
    if(UA_UInt32_decodeBinary(&secret, &offset, &secretLen) != UA_STATUSCODE_GOOD)
622
0
        goto cleanup;
623
624
    /* The decrypted data must be large enough to include the Encrypted Token
625
     * Secret Format and the length field must indicate enough data to include
626
     * the server nonce. */
627
0
    if(secret.length < sizeof(UA_UInt32) + serverSessionNonce.length ||
628
0
       secret.length < sizeof(UA_UInt32) + secretLen ||
629
0
       secretLen < serverSessionNonce.length)
630
0
        goto cleanup;
631
632
    /* If the Encrypted Token Secret contains padding, the padding must be
633
     * zeroes according to the 1.04.1 specification errata, chapter 3. */
634
0
    for(size_t i = sizeof(UA_UInt32) + secretLen; i < secret.length; i++) {
635
0
        if(secret.data[i] != 0)
636
0
            goto cleanup;
637
0
    }
638
639
    /* The server nonce must match according to the 1.04.1 specification errata,
640
     * chapter 3. */
641
0
    tokenpos = sizeof(UA_UInt32) + secretLen - serverSessionNonce.length;
642
0
    tokenNonce.length = serverSessionNonce.length;
643
0
    tokenNonce.data = &secret.data[tokenpos];
644
0
    if(!UA_ByteString_equal(&serverSessionNonce, &tokenNonce))
645
0
        goto cleanup;
646
647
    /* The password was decrypted successfully. Replace usertoken with the
648
     * decrypted password. The encryptionAlgorithm and policyId fields are left
649
     * in the UserToken as an indication for the AccessControl plugin that
650
     * evaluates the decrypted content. */
651
0
    size_t outLen = secretLen - serverSessionNonce.length;
652
0
    memcpy(tokenData->data, &secret.data[sizeof(UA_UInt32)], outLen);
653
0
    tokenData->length = outLen;
654
0
    res = UA_STATUSCODE_GOOD;
655
656
0
 cleanup:
657
0
    UA_ByteString_clear(&secret);
658
0
    return res;
659
0
}