open62541-sys 0.6.1

Low-level, unsafe bindings for the C11 library open62541, an open source and free implementation of OPC UA (OPC Unified Architecture).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 *    Copyright 2025 (c) Siemens AG (Author: Tin Raic)
 *    Copyright 2025-2026 (c) o6 Automation GmbH (Author: Julius Pfrommer)
 */

#include "ua_util_internal.h"

/************************/
/* ECC Encrypted Secret */
/************************/

typedef struct {
    /* Common Header */
    UA_NodeId typeId;
    UA_Byte encodingMask;
    UA_UInt32 length;
    UA_String securityPolicyUri;
    UA_ByteString certificate;
    UA_DateTime signingTime;
    UA_UInt16 keyDataLen;

    /* Policy Header*/
    UA_ByteString senderPublicKey;
    UA_ByteString receiverPublicKey;

    /* Payload */
    UA_ByteString nonce;
    UA_ByteString secret;
    /* UA_ByteString padding; // Computed when needed */

    /* Signature */
    UA_Byte* signature;
} UA_EccEncryptedSecretStruct;

static void
UA_EccEncryptedSecretStruct_init(UA_EccEncryptedSecretStruct* es) {
    memset(es, 0, sizeof(UA_EccEncryptedSecretStruct));
}

static void
UA_EccEncryptedSecretStruct_clear(UA_EccEncryptedSecretStruct* es) {
    UA_String_clear(&es->securityPolicyUri);
    UA_ByteString_clear(&es->certificate);
    UA_ByteString_clear(&es->senderPublicKey);
    UA_ByteString_clear(&es->receiverPublicKey);
    UA_ByteString_clear(&es->nonce);
    UA_ByteString_clear(&es->secret);
    UA_EccEncryptedSecretStruct_init(es);
}

static size_t
UA_EccEncryptedSecret_getCommonHeaderSize(const UA_EccEncryptedSecretStruct* src) {
    size_t len = 0;
    len += UA_calcSizeBinary(&src->typeId, &UA_TYPES[UA_TYPES_NODEID], NULL);
    len += UA_calcSizeBinary(&src->encodingMask, &UA_TYPES[UA_TYPES_BYTE], NULL);
    len += UA_calcSizeBinary(&src->length, &UA_TYPES[UA_TYPES_UINT32], NULL);
    len += UA_calcSizeBinary(&src->securityPolicyUri, &UA_TYPES[UA_TYPES_STRING], NULL);
    len += UA_calcSizeBinary(&src->certificate, &UA_TYPES[UA_TYPES_BYTESTRING], NULL);
    len += UA_calcSizeBinary(&src->signingTime, &UA_TYPES[UA_TYPES_DATETIME], NULL);
    len += UA_calcSizeBinary(&src->keyDataLen, &UA_TYPES[UA_TYPES_UINT16], NULL);
    return len;
}

static size_t
UA_EccEncryptedSecret_getPolicyHeaderSize(const UA_EccEncryptedSecretStruct* src) {
    size_t len = 0;
    len += UA_calcSizeBinary(&src->senderPublicKey, &UA_TYPES[UA_TYPES_BYTESTRING], NULL);
    len += UA_calcSizeBinary(&src->receiverPublicKey, &UA_TYPES[UA_TYPES_BYTESTRING], NULL);
    return len;
}

static UA_StatusCode
UA_EccEncryptedSecret_serializeCommonHeader(const UA_EccEncryptedSecretStruct *src,
                                            UA_Byte** bufPos, const UA_Byte* bufEnd) {
    UA_UInt32 length32 = (UA_UInt32)src->length;
    UA_StatusCode ret = UA_STATUSCODE_GOOD;
    ret |= UA_NodeId_encodeBinary(&src->typeId, bufPos, bufEnd);
    ret |= UA_Byte_encodeBinary(&src->encodingMask, bufPos, bufEnd);
    ret |= UA_UInt32_encodeBinary(&length32, bufPos, bufEnd);
    ret |= UA_String_encodeBinary(&src->securityPolicyUri, bufPos, bufEnd);
    ret |= UA_ByteString_encodeBinary(&src->certificate, bufPos, bufEnd);
    ret |= UA_DateTime_encodeBinary(&src->signingTime, bufPos, bufEnd);
    ret |= UA_UInt16_encodeBinary(&src->keyDataLen, bufPos, bufEnd);
    return ret;
}

static UA_StatusCode
UA_EccEncryptedSecret_serializePolicyHeader(const UA_EccEncryptedSecretStruct *src,
                                            UA_Byte** bufPos, const UA_Byte* bufEnd) {
    UA_StatusCode ret = UA_STATUSCODE_GOOD;
    ret |= UA_ByteString_encodeBinary(&src->senderPublicKey, bufPos, bufEnd);
    ret |= UA_ByteString_encodeBinary(&src->receiverPublicKey, bufPos, bufEnd);
    return ret;
}

static UA_StatusCode
UA_EccEncryptedSecret_deserializeCommonHeader(UA_EccEncryptedSecret *src,
                                              UA_EccEncryptedSecretStruct *dest,
                                              size_t* offset) {
    UA_StatusCode ret = UA_STATUSCODE_GOOD;
    ret |= UA_NodeId_decodeBinary(src, offset, &dest->typeId);
    ret |= UA_Byte_decodeBinary(src, offset, &dest->encodingMask);
    ret |= UA_UInt32_decodeBinary(src, offset, &dest->length);
    ret |= UA_String_decodeBinary(src, offset, &dest->securityPolicyUri);
    ret |= UA_ByteString_decodeBinary(src, offset, &dest->certificate);
    ret |= UA_DateTime_decodeBinary(src, offset, &dest->signingTime);
    ret |= UA_UInt16_decodeBinary(src, offset, &dest->keyDataLen);
    return ret;
}

static UA_StatusCode
UA_EccEncryptedSecret_deserializePolicyHeader(UA_EccEncryptedSecret *src,
                                              UA_EccEncryptedSecretStruct *dest,
                                              size_t* offset) {
    UA_StatusCode ret = UA_STATUSCODE_GOOD;
    ret |= UA_ByteString_decodeBinary(src, offset, &dest->senderPublicKey);
    ret |= UA_ByteString_decodeBinary(src, offset, &dest->receiverPublicKey);
    return ret;
}

UA_StatusCode
encryptUserIdentityTokenEcc(UA_Logger *logger, UA_SecureChannel *channel,
                            const UA_SecurityPolicy *sp, void *spContext,
                            UA_ByteString *tokenData,
                            const UA_ByteString serverSessionNonce,
                            const UA_ByteString serverEphemeralPubKey) {
    /* Extract some basic information from the SecurityPolicy. AEAD policies
     * (AES-GCM) expose a dedicated IV length (12 bytes) and append an
     * authentication tag after the ciphertext; legacy CBC policies use the
     * cipher block size as the IV length and have no tag. */
    UA_Boolean aead = UA_SecurityPolicy_isAead(sp);
    size_t symKeyLen = sp->symEncryptionAlgorithm.getLocalKeyLength(sp, spContext);
    size_t ivLen = (aead && sp->symEncryptionAlgorithm.getLocalIvLength) ?
        sp->symEncryptionAlgorithm.getLocalIvLength(sp, spContext) :
        sp->symEncryptionAlgorithm.getRemoteBlockSize(sp, spContext);
    size_t tagLen = aead ?
        sp->symSignatureAlgorithm.getLocalSignatureSize(sp, spContext) : 0;
    size_t sigLen = sp->asymSignatureAlgorithm.getRemoteSignatureSize(sp, spContext);
    UA_assert(symKeyLen > 0 && ivLen > 0);

    /* Filling out the EccEncryptedSecretStruct fields. The length field is
     * computed after. */
    UA_EccEncryptedSecretStruct secret;
    UA_EccEncryptedSecretStruct_init(&secret);
    secret.typeId = UA_NS0ID(ECCENCRYPTEDSECRET);
    secret.encodingMask = 0x01;
    secret.signingTime = UA_DateTime_now();

    /* Copy-only methods */
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
    retval |= UA_String_copy(&sp->policyUri, &secret.securityPolicyUri);
    retval |= UA_ByteString_copy(&sp->localCertificate, &secret.certificate);
    retval |= UA_ByteString_copy(&serverEphemeralPubKey, &secret.receiverPublicKey);
    retval |= UA_ByteString_copy(&serverSessionNonce, &secret.nonce);
    retval |= UA_ByteString_copy(tokenData, &secret.secret);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_EccEncryptedSecretStruct_clear(&secret);
        return retval;
    }

    /* Generate a new local ephemeral key. The private part remains persisted
     * inside the SecurityPolicy. */
    size_t ephKeyLen = sp->nonceLength; /* Also length of the ephemeral public key */
    retval = UA_ByteString_allocBuffer(&secret.senderPublicKey, ephKeyLen);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_EccEncryptedSecretStruct_clear(&secret);
        return retval;
    }
    secret.senderPublicKey.data[0] = 'e';
    secret.senderPublicKey.data[1] = 'p';
    secret.senderPublicKey.data[2] = 'h';
    retval = sp->generateNonce(sp, spContext, &secret.senderPublicKey);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(logger, channel,
                     "EccEncryptedSecret: Failed to generate local ephemeral key");
        UA_EccEncryptedSecretStruct_clear(&secret);
        return retval;
    }

    /* Compute the padding. the alignment block is 16 bytes for AEAD (AES-GCM)
     * and the IV/block size for CBC. The padding region is `paddingCount` bytes
     * of value paddingCount, followed by a 2-byte padding-size field
     * (PaddingSize | ExtraPaddingSize); those 2 bytes are included in the
     * alignment. */
    size_t blockSize = aead ? 16 : ivLen;
    size_t baseLen = UA_ByteString_calcSizeBinary(&secret.nonce) +
                     UA_ByteString_calcSizeBinary(&secret.secret);
    size_t modLen = (baseLen + 2) % blockSize;
    size_t paddingCount = (modLen == 0) ? 0 : (blockSize - modLen);
    if(paddingCount + secret.secret.length < blockSize)
        paddingCount += blockSize;
    size_t encryptedLength = baseLen + paddingCount + 2;

    /* Compute the total length including the headers and the signature */
    size_t signatureLen = sp->asymSignatureAlgorithm.
        getLocalSignatureSize(sp, spContext);
    secret.keyDataLen = (UA_UInt16)
        UA_EccEncryptedSecret_getPolicyHeaderSize(&secret);
    size_t totalLength = encryptedLength + tagLen + secret.keyDataLen +
        UA_EccEncryptedSecret_getCommonHeaderSize(&secret) + signatureLen;

    /* The EncryptedSecret "Length" field is the number of bytes that FOLLOW the
     * Length field, not the full serialized size. Subtract the common-header
     * prefix (TypeId NodeId + EncodingByte + the Length field itself = 9
     * bytes). */
    size_t headerPrefix =
        UA_calcSizeBinary(&secret.typeId, &UA_TYPES[UA_TYPES_NODEID], NULL) +
        UA_calcSizeBinary(&secret.encodingMask, &UA_TYPES[UA_TYPES_BYTE], NULL) +
        UA_calcSizeBinary(&secret.length, &UA_TYPES[UA_TYPES_UINT32], NULL);
    secret.length = (UA_UInt32)(totalLength - headerPrefix);

    /* Compute the symmetric key to encrypt */
    UA_ByteString symEncKeyMaterial;
    retval = UA_ByteString_allocBuffer(&symEncKeyMaterial, symKeyLen+ivLen);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_EccEncryptedSecretStruct_clear(&secret);
        return retval;
    }

    /* This is a (temporary) measure so that the salt generation function (for
     * the symmetric key derivation ) knows that the salt is generated for
     * session authentication (to choose the correct label) */
    /* TODO: find a better way to signal symmetric key generation for session
     * authentication */
    symEncKeyMaterial.data[0] = 0x03;
    symEncKeyMaterial.data[1] = 0x03;
    symEncKeyMaterial.data[2] = 0x04;
    retval = sp->generateKey(sp, spContext, &secret.receiverPublicKey,
                             &secret.senderPublicKey, &symEncKeyMaterial);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(logger, channel,
                             "EccEncryptedSecret: Failed to derive key material");
        UA_ByteString_clear(&symEncKeyMaterial);
        UA_EccEncryptedSecretStruct_clear(&secret);
        return retval;
    }

    /* Extracting the key and the initialization vector from the key material */
    UA_ByteString encKey = {symKeyLen, symEncKeyMaterial.data};
    UA_ByteString iv = {ivLen, &symEncKeyMaterial.data[symKeyLen]};
    retval |= sp->setLocalSymEncryptingKey(sp, spContext, &encKey);
    retval |= sp->setLocalSymIv(sp, spContext, &iv);
    UA_ByteString_clear(&symEncKeyMaterial);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(logger, channel,
                             "EccEncryptedSecret: Failed to set EncryptingKey/"
                             "IV in the SecurityPolicy");
        UA_EccEncryptedSecretStruct_clear(&secret);
        return retval;
    }

    /* Allocate the output buffer */
    UA_ByteString output;
    retval = UA_ByteString_allocBuffer(&output, totalLength);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_EccEncryptedSecretStruct_clear(&secret);
        return retval;
    }

    /* Encode all the content into the output buffer */
    UA_Byte* bufPos = output.data;
    UA_Byte* bufEnd = output.data + output.length;
    retval |= UA_EccEncryptedSecret_serializeCommonHeader(&secret, &bufPos, bufEnd);
    retval |= UA_EccEncryptedSecret_serializePolicyHeader(&secret, &bufPos, bufEnd);
    UA_Byte* payloadPos = bufPos;
    retval |= UA_ByteString_encodeBinary(&secret.nonce, &bufPos, bufEnd);
    retval |= UA_ByteString_encodeBinary(&secret.secret, &bufPos, bufEnd);
    UA_Byte pad = (UA_Byte)(paddingCount & 0xFF);
    for(size_t i = 0; i < paddingCount; i++) {
        *bufPos = pad;
        bufPos++;
    }
    /* 2-byte padding-size field: PaddingSize byte + ExtraPaddingSize byte.
     * For paddingCount < 256 this equals the little-endian UInt16. */
    UA_UInt16 paddingCount16 = (UA_UInt16)paddingCount;
    retval |= UA_UInt16_encodeBinary(&paddingCount16, &bufPos, bufEnd);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_EccEncryptedSecretStruct_clear(&secret);
        UA_ByteString_clear(&output);
        return retval;
    }

    /* Encrypt the payload region in-situ. For AEAD (AES-GCM) the GCM primitive
     * writes the authentication tag into the last `tagLen` bytes of the buffer
     * it is given, so the region passed in spans the plaintext plus the
     * reserved tag bytes. The AAD is the EccEncryptedSecret header preceding
     * the encrypted region, and the IV is used unmasked (tokenId / sequence
     * number = 0). */
    UA_ByteString payload = {(size_t)(bufPos - payloadPos) + tagLen, payloadPos};
    if(aead) {
        UA_ByteString aad = {(size_t)(payloadPos - output.data), output.data};
        retval |= sp->setMessageSecurityParameters(sp, spContext, 0, 0, &aad);
    }
    retval |= sp->symEncryptionAlgorithm.encrypt(sp, spContext, &payload);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(logger, channel,
                     "EccEncryptedSecret: Failed to encrypt the payload");
        UA_EccEncryptedSecretStruct_clear(&secret);
        UA_ByteString_clear(&output);
        return retval;
    }

    /* The authentication tag (if any) now occupies the next tagLen bytes;
     * advance past it to the signature slot. */
    bufPos += tagLen;
    UA_assert(bufPos + sigLen == bufEnd);

    /* Compute the overall signature over everything except the signature. */
    UA_ByteString sigContent = {(size_t)(bufPos - output.data), output.data};
    UA_ByteString signature = {sigLen, bufPos};
    retval = sp->asymSignatureAlgorithm.sign(sp, spContext, &sigContent, &signature);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(logger, channel,
                     "EccEncryptedSecret: Failed to sign the EccEncryptedSecret");
        UA_EccEncryptedSecretStruct_clear(&secret);
        UA_ByteString_clear(&output);
        return retval;
    }

    /* Replace tokenData with the output */
    UA_ByteString_clear(tokenData);
    *tokenData = output;

    UA_EccEncryptedSecretStruct_clear(&secret);
    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
decryptUserTokenEcc(UA_Logger *logger, UA_SecureChannel *channel,
                    const UA_SecurityPolicy *sp, void *spContext,
                    UA_ByteString sessionServerNonce,
                    UA_EccEncryptedSecret *es) {
    /* ECC usage verified before calling into this function */
    UA_assert(UA_SecurityPolicy_isEcc(sp));

    /* Define and initialize in case of clean-up */
    UA_StatusCode res = UA_STATUSCODE_GOOD;
    UA_EccEncryptedSecretStruct esd;
    UA_EccEncryptedSecretStruct_init(&esd);
    UA_ByteString symEncKeyMaterial = UA_BYTESTRING_NULL;
    UA_ByteString pass = UA_BYTESTRING_NULL;

    size_t offset = 0;
    res = UA_EccEncryptedSecret_deserializeCommonHeader(es, &esd, &offset);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Failed to decode the common header");
        goto cleanecc;
    }

    /* Check TypeId */
    UA_NodeId eccTypeId = UA_NS0ID(ECCENCRYPTEDSECRET);
    if(!UA_NodeId_equal(&eccTypeId, &esd.typeId) ||
       esd.encodingMask != 0x01 ||
       !UA_String_equal(&esd.securityPolicyUri, &sp->policyUri)) {
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Inconsistent common header");
        res = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
        goto cleanecc;
    }

    /* The "Length" field counts the bytes following the Length field, so the
     * end of the secret is (Length + the common-header prefix: TypeId NodeId +
     * EncodingByte + Length field). Validate it and use it (instead of the
     * whole ByteString size) for the payload/signature bounds. */
    size_t headerPrefix =
        UA_calcSizeBinary(&esd.typeId, &UA_TYPES[UA_TYPES_NODEID], NULL) +
        UA_calcSizeBinary(&esd.encodingMask, &UA_TYPES[UA_TYPES_BYTE], NULL) +
        UA_calcSizeBinary(&esd.length, &UA_TYPES[UA_TYPES_UINT32], NULL);
    size_t endOfSecret = (size_t)esd.length + headerPrefix;
    if(endOfSecret > es->length || endOfSecret <= offset) {
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Inconsistent Length field");
        res = UA_STATUSCODE_BADDECODINGERROR;
        goto cleanecc;
    }

    /* Verify signature */
    size_t sigLen = sp->asymSignatureAlgorithm.getRemoteSignatureSize(sp, spContext);
    size_t signedDataLen = endOfSecret - sigLen;
    UA_ByteString signedData = {signedDataLen, es->data};
    UA_ByteString signature = {sigLen, &es->data[signedDataLen]};
    res = sp->asymSignatureAlgorithm.verify(sp, spContext, &signedData, &signature);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Signature verification failed");
        goto cleanecc;
    }

    size_t oldoffset = offset;
    res = UA_EccEncryptedSecret_deserializePolicyHeader(es, &esd, &offset);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Failed to decode the policy header");
        goto cleanecc;
    }

    /* Sanity check of the key data length.
     * This needs to include the 2x4 byte length fields. */
    if(esd.keyDataLen != (UA_UInt16)(offset - oldoffset)) {
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Inconstent KeyDataLength");
        res = UA_STATUSCODE_BADIDENTITYTOKENINVALID;
        goto cleanecc;
    }

    /* Check the payload length */
    if(endOfSecret <= offset + sigLen) {
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Inconstent payload / signature length");
        res = UA_STATUSCODE_BADIDENTITYTOKENINVALID;
        goto cleanecc;
    }
    UA_ByteString payload = {endOfSecret - offset - sigLen, es->data + offset};

    /* Deriving (remote) symmetric encryption key to decrypt the payload.
     * AEAD policies (AES-GCM) use a dedicated 12-byte IV length; legacy CBC
     * uses the cipher block size. */
    UA_Boolean aead = UA_SecurityPolicy_isAead(sp);
    size_t symKeyLen = sp->symEncryptionAlgorithm.getRemoteKeyLength(sp, spContext);
    size_t ivLen = (aead && sp->symEncryptionAlgorithm.getLocalIvLength) ?
        sp->symEncryptionAlgorithm.getLocalIvLength(sp, spContext) :
        sp->symEncryptionAlgorithm.getRemoteBlockSize(sp, spContext);
    res = UA_ByteString_allocBuffer(&symEncKeyMaterial, symKeyLen+ivLen);
    if(res != UA_STATUSCODE_GOOD)
        goto cleanecc;

    /* This is a (temporary) measure so that the salt generation function (for
     * the symmetric key derivation ) knows that the salt is generated for
     * session authentication (to choose the correct label) */
    /* TODO: find a better way to signal symmetric key generation for session
     * authentication */
    symEncKeyMaterial.data[0] = 0x03;
    symEncKeyMaterial.data[1] = 0x03;
    symEncKeyMaterial.data[2] = 0x04;

    /* Call logic for server for session authentication: receiver public key is
     * local (server), sender public key is remote (client) */
    res = sp->generateKey(sp, spContext, &esd.receiverPublicKey,
                          &esd.senderPublicKey, &symEncKeyMaterial);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Failed to derive key material");
        goto cleanecc;
    }

    /* Extract the encryption key and the initialization vector */
    UA_ByteString encKey = {symKeyLen, symEncKeyMaterial.data};
    UA_ByteString iv = {ivLen, &symEncKeyMaterial.data[symKeyLen]};

    /* Set IV and RemoteEncryptingKey. That is all we need to decode the
     * secret. */
    res |= sp->setRemoteSymEncryptingKey(sp, spContext, &encKey);
    res |= sp->setRemoteSymIv(sp, spContext, &iv);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Failed to set IV/RemoteSymEncryptingKey");
        goto cleanecc;
    }

    /* For AEAD (AES-GCM), the AAD is the EccEncryptedSecret header that
     * precedes the encrypted region and the IV is used unmasked (tokenId /
     * sequence number = 0). The 16-byte tag at the end of the payload is
     * verified (and stripped) by the decrypt. */
    if(aead) {
        UA_ByteString aad = {(size_t)(payload.data - es->data), es->data};
        res = sp->setMessageSecurityParameters(sp, spContext, 0, 0, &aad);
        if(res != UA_STATUSCODE_GOOD) {
            UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                                 "Failed to set AEAD parameters");
            goto cleanecc;
        }
    }

    /* Decrypt payload (password) */
    res = sp->symEncryptionAlgorithm.decrypt(sp, spContext, &payload);
    if(res != UA_STATUSCODE_GOOD) {
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Failed to decrypt the payload");
        goto cleanecc;
    }

    /* Decode nonce and secret */
    offset = 0; /* Within the payload */
    UA_ByteString nonce;
    UA_StatusCode ret = UA_STATUSCODE_GOOD;
    ret |= UA_ByteString_decodeBinary(&payload, &offset, &nonce);
    ret |= UA_ByteString_decodeBinary(&payload, &offset, &pass);
    if(ret != UA_STATUSCODE_GOOD) {
        UA_ByteString_clear(&nonce);
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Failed to decode the payload");
        goto cleanecc;
    }

    /* Compare the nonce */
    UA_Boolean nonceMatch = UA_ByteString_equal(&sessionServerNonce, &nonce);
    UA_ByteString_clear(&nonce);
    if(!nonceMatch) {
        UA_LOG_ERROR_CHANNEL(logger, channel, "EccEncryptedSecret: "
                             "Nonce does not match");
        res = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
        goto cleanecc;
    }

    /* Decode the padding length and validate */
    UA_UInt16 paddingSize = 0;
    size_t paddingOffset = payload.length - 2;
    UA_UInt16_decodeBinary(&payload, &paddingOffset, &paddingSize);
    UA_Byte padd = (UA_Byte)paddingSize;
    for(; offset < payload.length-2; offset++) {
        if(payload.data[offset] != padd) {
            UA_LOG_ERROR_CHANNEL(logger, channel,
                                 "EccEncryptedSecret: Inconsistent padding");
            res = UA_STATUSCODE_BADSECURITYCHECKSFAILED;
            goto cleanecc;
        }
    }

    /* Copy the password to the output */
    memcpy(es->data, pass.data, pass.length);
    es->length = pass.length;

cleanecc:
    UA_EccEncryptedSecretStruct_clear(&esd);
    UA_ByteString_clear(&symEncKeyMaterial);
    UA_ByteString_clear(&pass);
    return res;
}

/***************************/
/* Legacy Encrypted Secret */
/***************************/

UA_StatusCode
encryptSecretLegacy(const UA_SecurityPolicy *sp, void *spContext,
                    const UA_ByteString serverSessionNonce,
                    UA_ByteString *tokenData) {
    /* Compute the encrypted length (at least one byte padding) */
    size_t plainTextBlockSize = sp->asymEncryptionAlgorithm.
        getRemotePlainTextBlockSize(sp, spContext);
    size_t encryptedBlockSize = sp->asymEncryptionAlgorithm.
        getRemoteBlockSize(sp, spContext);
    UA_UInt32 length =
        (UA_UInt32)(tokenData->length + serverSessionNonce.length);
    UA_UInt32 totalLength = length + 4; /* Including the length field */
    size_t blocks = totalLength / plainTextBlockSize;
    if(totalLength % plainTextBlockSize != 0)
        blocks++;
    size_t encryptedLength = blocks * encryptedBlockSize;

    /* Allocate memory for the encrypted secret */
    UA_ByteString encrypted;
    UA_StatusCode res = UA_ByteString_allocBuffer(&encrypted, encryptedLength);
    if(res != UA_STATUSCODE_GOOD)
        return res;

    /* Copy the secret and the nonce into the output */
    UA_Byte *pos = encrypted.data;
    const UA_Byte *end = &encrypted.data[encrypted.length];
    res = UA_UInt32_encodeBinary(&length, &pos, end);
    memcpy(pos, tokenData->data, tokenData->length);
    memcpy(&pos[tokenData->length], serverSessionNonce.data,
           serverSessionNonce.length);
    UA_assert(res == UA_STATUSCODE_GOOD);

    /* Add padding
     *
     * 7.36.2.2 Legacy Encrypted Token Secret Format: A Client should not add
     * any padding after the secret. If a Client adds padding then all bytes
     * shall be zero. A Server shall check for padding added by Clients and
     * ensure that all padding bytes are zeros. */
    size_t paddedLength = plainTextBlockSize * blocks;
    for(size_t i = totalLength; i < paddedLength; i++)
        encrypted.data[i] = 0;
    encrypted.length = paddedLength;

    /* Encrypt */
    res = sp->asymEncryptionAlgorithm.encrypt(sp, spContext, &encrypted);
    if(res != UA_STATUSCODE_GOOD) {
        UA_ByteString_clear(&encrypted);
        return res;
    }

    /* Replace the tokenData with the output */
    encrypted.length = encryptedLength;
    UA_ByteString_clear(tokenData);
    *tokenData = encrypted;
    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
decryptSecretLegacy(const UA_SecurityPolicy *sp, void *spContext,
                    const UA_ByteString serverSessionNonce,
                    UA_ByteString *tokenData) {
    UA_UInt32 secretLen = 0;
    UA_ByteString secret, tokenNonce;
    size_t tokenpos = 0;
    size_t offset = 0;
    const UA_SecurityPolicyEncryptionAlgorithm *asymEnc = &sp->asymEncryptionAlgorithm;

    /* Decrypt the secret */
    UA_StatusCode res = UA_STATUSCODE_BADIDENTITYTOKENINVALID;
    if(UA_ByteString_copy(tokenData, &secret) != UA_STATUSCODE_GOOD ||
       asymEnc->decrypt(sp, spContext, &secret) != UA_STATUSCODE_GOOD)
        goto cleanup;

    /* The secret starts with a UInt32 length for the content */
    if(UA_UInt32_decodeBinary(&secret, &offset, &secretLen) != UA_STATUSCODE_GOOD)
        goto cleanup;

    /* The decrypted data must be large enough to include the Encrypted Token
     * Secret Format and the length field must indicate enough data to include
     * the server nonce. */
    if(secret.length < sizeof(UA_UInt32) + serverSessionNonce.length ||
       secret.length < sizeof(UA_UInt32) + secretLen ||
       secretLen < serverSessionNonce.length)
        goto cleanup;

    /* If the Encrypted Token Secret contains padding, the padding must be
     * zeroes according to the 1.04.1 specification errata, chapter 3. */
    for(size_t i = sizeof(UA_UInt32) + secretLen; i < secret.length; i++) {
        if(secret.data[i] != 0)
            goto cleanup;
    }

    /* The server nonce must match according to the 1.04.1 specification errata,
     * chapter 3. */
    tokenpos = sizeof(UA_UInt32) + secretLen - serverSessionNonce.length;
    tokenNonce.length = serverSessionNonce.length;
    tokenNonce.data = &secret.data[tokenpos];
    if(!UA_ByteString_equal(&serverSessionNonce, &tokenNonce))
        goto cleanup;

    /* The password was decrypted successfully. Replace usertoken with the
     * decrypted password. The encryptionAlgorithm and policyId fields are left
     * in the UserToken as an indication for the AccessControl plugin that
     * evaluates the decrypted content. */
    size_t outLen = secretLen - serverSessionNonce.length;
    memcpy(tokenData->data, &secret.data[sizeof(UA_UInt32)], outLen);
    tokenData->length = outLen;
    res = UA_STATUSCODE_GOOD;

 cleanup:
    UA_ByteString_clear(&secret);
    return res;
}