Coverage Report

Created: 2026-08-31 07:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/open62541_15/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
    size_t endOfSecret = (size_t)esd.length + headerPrefix;
374
0
    if(endOfSecret > es->length || endOfSecret <= offset) {
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
381
    /* Verify signature */
382
0
    size_t sigLen = sp->asymSignatureAlgorithm.getRemoteSignatureSize(sp, spContext);
383
0
    size_t signedDataLen = endOfSecret - sigLen;
384
0
    UA_ByteString signedData = {signedDataLen, es->data};
385
0
    UA_ByteString signature = {sigLen, &es->data[signedDataLen]};
386
0
    res = sp->asymSignatureAlgorithm.verify(sp, spContext, &signedData, &signature);
387
0
    if(res != UA_STATUSCODE_GOOD) {
388
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
389
0
                             "Signature verification failed");
390
0
        goto cleanecc;
391
0
    }
392
393
0
    size_t oldoffset = offset;
394
0
    res = UA_EccEncryptedSecret_deserializePolicyHeader(es, &esd, &offset);
395
0
    if(res != UA_STATUSCODE_GOOD) {
396
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
397
0
                             "Failed to decode the policy header");
398
0
        goto cleanecc;
399
0
    }
400
401
    /* Sanity check of the key data length.
402
     * This needs to include the 2x4 byte length fields. */
403
0
    if(esd.keyDataLen != (UA_UInt16)(offset - oldoffset)) {
404
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
405
0
                             "Inconstent KeyDataLength");
406
0
        res = UA_STATUSCODE_BADIDENTITYTOKENINVALID;
407
0
        goto cleanecc;
408
0
    }
409
410
    /* Check the payload length */
411
0
    if(endOfSecret <= offset + sigLen) {
412
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
413
0
                             "Inconstent payload / signature length");
414
0
        res = UA_STATUSCODE_BADIDENTITYTOKENINVALID;
415
0
        goto cleanecc;
416
0
    }
417
0
    UA_ByteString payload = {endOfSecret - offset - sigLen, es->data + offset};
418
419
    /* Deriving (remote) symmetric encryption key to decrypt the payload.
420
     * AEAD policies (AES-GCM) use a dedicated 12-byte IV length; legacy CBC
421
     * uses the cipher block size. */
422
0
    UA_Boolean aead = UA_SecurityPolicy_isAead(sp);
423
0
    size_t symKeyLen = sp->symEncryptionAlgorithm.getRemoteKeyLength(sp, spContext);
424
0
    size_t ivLen = (aead && sp->symEncryptionAlgorithm.getLocalIvLength) ?
425
0
        sp->symEncryptionAlgorithm.getLocalIvLength(sp, spContext) :
426
0
        sp->symEncryptionAlgorithm.getRemoteBlockSize(sp, spContext);
427
0
    res = UA_ByteString_allocBuffer(&symEncKeyMaterial, symKeyLen+ivLen);
428
0
    if(res != UA_STATUSCODE_GOOD)
429
0
        goto cleanecc;
430
431
    /* This is a (temporary) measure so that the salt generation function (for
432
     * the symmetric key derivation ) knows that the salt is generated for
433
     * session authentication (to choose the correct label) */
434
    /* TODO: find a better way to signal symmetric key generation for session
435
     * authentication */
436
0
    symEncKeyMaterial.data[0] = 0x03;
437
0
    symEncKeyMaterial.data[1] = 0x03;
438
0
    symEncKeyMaterial.data[2] = 0x04;
439
440
    /* Call logic for server for session authentication: receiver public key is
441
     * local (server), sender public key is remote (client) */
442
0
    res = sp->generateKey(sp, spContext, &esd.receiverPublicKey,
443
0
                          &esd.senderPublicKey, &symEncKeyMaterial);
444
0
    if(res != UA_STATUSCODE_GOOD) {
445
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
446
0
                             "Failed to derive key material");
447
0
        goto cleanecc;
448
0
    }
449
450
    /* Extract the encryption key and the initialization vector */
451
0
    UA_ByteString encKey = {symKeyLen, symEncKeyMaterial.data};
452
0
    UA_ByteString iv = {ivLen, &symEncKeyMaterial.data[symKeyLen]};
453
454
    /* Set IV and RemoteEncryptingKey. That is all we need to decode the
455
     * secret. */
456
0
    res |= sp->setRemoteSymEncryptingKey(sp, spContext, &encKey);
457
0
    res |= sp->setRemoteSymIv(sp, spContext, &iv);
458
0
    if(res != UA_STATUSCODE_GOOD) {
459
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
460
0
                             "Failed to set IV/RemoteSymEncryptingKey");
461
0
        goto cleanecc;
462
0
    }
463
464
    /* For AEAD (AES-GCM), the AAD is the EccEncryptedSecret header that
465
     * precedes the encrypted region and the IV is used unmasked (tokenId /
466
     * sequence number = 0). The 16-byte tag at the end of the payload is
467
     * verified (and stripped) by the decrypt. */
468
0
    if(aead) {
469
0
        UA_ByteString aad = {(size_t)(payload.data - es->data), es->data};
470
0
        res = sp->setMessageSecurityParameters(sp, spContext, 0, 0, &aad);
471
0
        if(res != UA_STATUSCODE_GOOD) {
472
0
            UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
473
0
                                 "Failed to set AEAD parameters");
474
0
            goto cleanecc;
475
0
        }
476
0
    }
477
478
    /* Decrypt payload (password) */
479
0
    res = sp->symEncryptionAlgorithm.decrypt(sp, spContext, &payload);
480
0
    if(res != UA_STATUSCODE_GOOD) {
481
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
482
0
                             "Failed to decrypt the payload");
483
0
        goto cleanecc;
484
0
    }
485
486
    /* Decode nonce and secret */
487
0
    offset = 0; /* Within the payload */
488
0
    UA_ByteString nonce;
489
0
    UA_StatusCode ret = UA_STATUSCODE_GOOD;
490
0
    ret |= UA_ByteString_decodeBinary(&payload, &offset, &nonce);
491
0
    ret |= UA_ByteString_decodeBinary(&payload, &offset, &pass);
492
0
    if(ret != UA_STATUSCODE_GOOD) {
493
0
        UA_ByteString_clear(&nonce);
494
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
495
0
                             "Failed to decode the payload");
496
0
        goto cleanecc;
497
0
    }
498
499
    /* Compare the nonce */
500
0
    UA_Boolean nonceMatch = UA_ByteString_equal(&sessionServerNonce, &nonce);
501
0
    UA_ByteString_clear(&nonce);
502
0
    if(!nonceMatch) {
503
0
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
504
0
                             "Nonce does not match");
505
0
        res = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
506
0
        goto cleanecc;
507
0
    }
508
509
    /* Decode the padding length and validate */
510
0
    UA_UInt16 paddingSize = 0;
511
0
    size_t paddingOffset = payload.length - 2;
512
0
    UA_UInt16_decodeBinary(&payload, &paddingOffset, &paddingSize);
513
0
    UA_Byte padd = (UA_Byte)paddingSize;
514
0
    for(; offset < payload.length-2; offset++) {
515
0
        if(payload.data[offset] != padd) {
516
0
            UA_LOG_ERROR_CHANNEL(logger, channel,
517
0
                                 "EccEncryptedSecret: Inconsistent padding");
518
0
            res = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
519
0
            goto cleanecc;
520
0
        }
521
0
    }
522
523
    /* Copy the password to the output */
524
0
    memcpy(es->data, pass.data, pass.length);
525
0
    es->length = pass.length;
526
527
0
cleanecc:
528
0
    UA_EccEncryptedSecretStruct_clear(&esd);
529
0
    UA_ByteString_clear(&symEncKeyMaterial);
530
0
    UA_ByteString_clear(&pass);
531
0
    return res;
532
0
}
533
534
/***************************/
535
/* Legacy Encrypted Secret */
536
/***************************/
537
538
UA_StatusCode
539
encryptSecretLegacy(const UA_SecurityPolicy *sp, void *spContext,
540
                    const UA_ByteString serverSessionNonce,
541
0
                    UA_ByteString *tokenData) {
542
    /* Compute the encrypted length (at least one byte padding) */
543
0
    size_t plainTextBlockSize = sp->asymEncryptionAlgorithm.
544
0
        getRemotePlainTextBlockSize(sp, spContext);
545
0
    size_t encryptedBlockSize = sp->asymEncryptionAlgorithm.
546
0
        getRemoteBlockSize(sp, spContext);
547
0
    UA_UInt32 length =
548
0
        (UA_UInt32)(tokenData->length + serverSessionNonce.length);
549
0
    UA_UInt32 totalLength = length + 4; /* Including the length field */
550
0
    size_t blocks = totalLength / plainTextBlockSize;
551
0
    if(totalLength % plainTextBlockSize != 0)
552
0
        blocks++;
553
0
    size_t encryptedLength = blocks * encryptedBlockSize;
554
555
    /* Allocate memory for the encrypted secret */
556
0
    UA_ByteString encrypted;
557
0
    UA_StatusCode res = UA_ByteString_allocBuffer(&encrypted, encryptedLength);
558
0
    if(res != UA_STATUSCODE_GOOD)
559
0
        return res;
560
561
    /* Copy the secret and the nonce into the output */
562
0
    UA_Byte *pos = encrypted.data;
563
0
    const UA_Byte *end = &encrypted.data[encrypted.length];
564
0
    res = UA_UInt32_encodeBinary(&length, &pos, end);
565
0
    memcpy(pos, tokenData->data, tokenData->length);
566
0
    memcpy(&pos[tokenData->length], serverSessionNonce.data,
567
0
           serverSessionNonce.length);
568
0
    UA_assert(res == UA_STATUSCODE_GOOD);
569
570
    /* Add padding
571
     *
572
     * 7.36.2.2 Legacy Encrypted Token Secret Format: A Client should not add
573
     * any padding after the secret. If a Client adds padding then all bytes
574
     * shall be zero. A Server shall check for padding added by Clients and
575
     * ensure that all padding bytes are zeros. */
576
0
    size_t paddedLength = plainTextBlockSize * blocks;
577
0
    for(size_t i = totalLength; i < paddedLength; i++)
578
0
        encrypted.data[i] = 0;
579
0
    encrypted.length = paddedLength;
580
581
    /* Encrypt */
582
0
    res = sp->asymEncryptionAlgorithm.encrypt(sp, spContext, &encrypted);
583
0
    if(res != UA_STATUSCODE_GOOD) {
584
0
        UA_ByteString_clear(&encrypted);
585
0
        return res;
586
0
    }
587
588
    /* Replace the tokenData with the output */
589
0
    encrypted.length = encryptedLength;
590
0
    UA_ByteString_clear(tokenData);
591
0
    *tokenData = encrypted;
592
0
    return UA_STATUSCODE_GOOD;
593
0
}
594
595
UA_StatusCode
596
decryptSecretLegacy(const UA_SecurityPolicy *sp, void *spContext,
597
                    const UA_ByteString serverSessionNonce,
598
0
                    UA_ByteString *tokenData) {
599
0
    UA_UInt32 secretLen = 0;
600
0
    UA_ByteString secret, tokenNonce;
601
0
    size_t tokenpos = 0;
602
0
    size_t offset = 0;
603
0
    const UA_SecurityPolicyEncryptionAlgorithm *asymEnc = &sp->asymEncryptionAlgorithm;
604
605
    /* Decrypt the secret */
606
0
    UA_StatusCode res = UA_STATUSCODE_BADIDENTITYTOKENINVALID;
607
0
    if(UA_ByteString_copy(tokenData, &secret) != UA_STATUSCODE_GOOD ||
608
0
       asymEnc->decrypt(sp, spContext, &secret) != UA_STATUSCODE_GOOD)
609
0
        goto cleanup;
610
611
    /* The secret starts with a UInt32 length for the content */
612
0
    if(UA_UInt32_decodeBinary(&secret, &offset, &secretLen) != UA_STATUSCODE_GOOD)
613
0
        goto cleanup;
614
615
    /* The decrypted data must be large enough to include the Encrypted Token
616
     * Secret Format and the length field must indicate enough data to include
617
     * the server nonce. */
618
0
    if(secret.length < sizeof(UA_UInt32) + serverSessionNonce.length ||
619
0
       secret.length < sizeof(UA_UInt32) + secretLen ||
620
0
       secretLen < serverSessionNonce.length)
621
0
        goto cleanup;
622
623
    /* If the Encrypted Token Secret contains padding, the padding must be
624
     * zeroes according to the 1.04.1 specification errata, chapter 3. */
625
0
    for(size_t i = sizeof(UA_UInt32) + secretLen; i < secret.length; i++) {
626
0
        if(secret.data[i] != 0)
627
0
            goto cleanup;
628
0
    }
629
630
    /* The server nonce must match according to the 1.04.1 specification errata,
631
     * chapter 3. */
632
0
    tokenpos = sizeof(UA_UInt32) + secretLen - serverSessionNonce.length;
633
0
    tokenNonce.length = serverSessionNonce.length;
634
0
    tokenNonce.data = &secret.data[tokenpos];
635
0
    if(!UA_ByteString_equal(&serverSessionNonce, &tokenNonce))
636
0
        goto cleanup;
637
638
    /* The password was decrypted successfully. Replace usertoken with the
639
     * decrypted password. The encryptionAlgorithm and policyId fields are left
640
     * in the UserToken as an indication for the AccessControl plugin that
641
     * evaluates the decrypted content. */
642
0
    size_t outLen = secretLen - serverSessionNonce.length;
643
0
    memcpy(tokenData->data, &secret.data[sizeof(UA_UInt32)], outLen);
644
0
    tokenData->length = outLen;
645
0
    res = UA_STATUSCODE_GOOD;
646
647
0
 cleanup:
648
0
    UA_ByteString_clear(&secret);
649
0
    return res;
650
0
}