Coverage Report

Created: 2025-12-20 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/nss/lib/ssl/tls13hkdf.c
Line
Count
Source
1
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
/*
3
 * TLS 1.3 Protocol
4
 *
5
 * This Source Code Form is subject to the terms of the Mozilla Public
6
 * License, v. 2.0. If a copy of the MPL was not distributed with this
7
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8
9
#include "keyhi.h"
10
#include "pk11func.h"
11
#include "secitem.h"
12
#include "ssl.h"
13
#include "sslt.h"
14
#include "sslerr.h"
15
#include "sslimpl.h"
16
17
/* This table contains the mapping between TLS hash identifiers and the
18
 * PKCS#11 identifiers */
19
static const struct {
20
    SSLHashType hash;
21
    CK_MECHANISM_TYPE pkcs11Mech;
22
    unsigned int hashSize;
23
} kTlsHkdfInfo[] = {
24
    { ssl_hash_none, 0, 0 },
25
    { ssl_hash_md5, 0, 0 },
26
    { ssl_hash_sha1, 0, 0 },
27
    { ssl_hash_sha224, 0 },
28
    { ssl_hash_sha256, CKM_SHA256, 32 },
29
    { ssl_hash_sha384, CKM_SHA384, 48 },
30
    { ssl_hash_sha512, CKM_SHA512, 64 }
31
};
32
33
SECStatus
34
tls13_HkdfExtract(PK11SymKey *ikm1, PK11SymKey *ikm2, SSLHashType baseHash,
35
                  PK11SymKey **prkp)
36
23.8k
{
37
23.8k
    CK_HKDF_PARAMS params;
38
23.8k
    SECItem paramsi;
39
23.8k
    PK11SymKey *prk;
40
23.8k
    static const PRUint8 zeroKeyBuf[HASH_LENGTH_MAX];
41
23.8k
    SECItem zeroKeyItem = { siBuffer, CONST_CAST(PRUint8, zeroKeyBuf), kTlsHkdfInfo[baseHash].hashSize };
42
23.8k
    PK11SlotInfo *slot = NULL;
43
23.8k
    PK11SymKey *newIkm2 = NULL;
44
23.8k
    PK11SymKey *newIkm1 = NULL;
45
23.8k
    SECStatus rv;
46
47
23.8k
    params.bExtract = CK_TRUE;
48
23.8k
    params.bExpand = CK_FALSE;
49
23.8k
    params.prfHashMechanism = kTlsHkdfInfo[baseHash].pkcs11Mech;
50
23.8k
    params.pInfo = NULL;
51
23.8k
    params.ulInfoLen = 0UL;
52
23.8k
    params.pSalt = NULL;
53
23.8k
    params.ulSaltLen = 0UL;
54
23.8k
    params.hSaltKey = CK_INVALID_HANDLE;
55
56
23.8k
    if (!ikm1) {
57
        /* PKCS #11 v3.0 has and explict NULL value, which equates to
58
         * a sequence of zeros equal in length to the HMAC. */
59
13.1k
        params.ulSaltType = CKF_HKDF_SALT_NULL;
60
13.1k
    } else {
61
        /* PKCS #11 v3.0 can take the salt as a key handle */
62
10.6k
        params.hSaltKey = PK11_GetSymKeyHandle(ikm1);
63
10.6k
        params.ulSaltType = CKF_HKDF_SALT_KEY;
64
65
        /* if we have both keys, make sure they are in the same slot */
66
10.6k
        if (ikm2) {
67
5.33k
            rv = PK11_SymKeysToSameSlot(CKM_HKDF_DERIVE,
68
5.33k
                                        CKA_DERIVE, CKA_DERIVE,
69
5.33k
                                        ikm2, ikm1, &newIkm2, &newIkm1);
70
5.33k
            if (rv != SECSuccess) {
71
0
                SECItem *salt;
72
                /* couldn't move the keys, try extracting the salt */
73
0
                rv = PK11_ExtractKeyValue(ikm1);
74
0
                if (rv != SECSuccess)
75
0
                    return rv;
76
0
                salt = PK11_GetKeyData(ikm1);
77
0
                if (!salt)
78
0
                    return SECFailure;
79
0
                PORT_Assert(salt->len > 0);
80
                /* Set up for Salt as Data instead of Salt as key */
81
0
                params.pSalt = salt->data;
82
0
                params.ulSaltLen = salt->len;
83
0
                params.ulSaltType = CKF_HKDF_SALT_DATA;
84
0
            }
85
            /* use the new keys */
86
5.33k
            if (newIkm1) {
87
                /* we've moved the key, get the handle for the new key */
88
5.32k
                params.hSaltKey = PK11_GetSymKeyHandle(newIkm1);
89
                /* we don't use ikm1 after this, so don't bother setting it */
90
5.32k
            }
91
5.33k
            if (newIkm2) {
92
                /* new ikm2 key, use the new key */
93
0
                ikm2 = newIkm2;
94
0
            }
95
5.33k
        }
96
10.6k
    }
97
23.8k
    paramsi.data = (unsigned char *)&params;
98
23.8k
    paramsi.len = sizeof(params);
99
100
23.8k
    PORT_Assert(kTlsHkdfInfo[baseHash].pkcs11Mech);
101
23.8k
    PORT_Assert(kTlsHkdfInfo[baseHash].hashSize);
102
23.8k
    PORT_Assert(kTlsHkdfInfo[baseHash].hash == baseHash);
103
104
    /* A zero ikm2 is a key of hash-length 0s. */
105
23.8k
    if (!ikm2) {
106
        /* if we have ikm1, put the zero key in the same slot */
107
10.6k
        slot = ikm1 ? PK11_GetSlotFromKey(ikm1) : PK11_GetBestSlot(CKM_HKDF_DERIVE, NULL);
108
10.6k
        if (!slot) {
109
0
            return SECFailure;
110
0
        }
111
112
10.6k
        newIkm2 = PK11_ImportDataKey(slot, CKM_HKDF_DERIVE, PK11_OriginUnwrap,
113
10.6k
                                     CKA_DERIVE, &zeroKeyItem, NULL);
114
10.6k
        if (!newIkm2) {
115
0
            return SECFailure;
116
0
        }
117
10.6k
        ikm2 = newIkm2;
118
10.6k
    }
119
23.8k
    PORT_Assert(ikm2);
120
121
23.8k
    PRINT_BUF(50, (NULL, "HKDF Extract: IKM1/Salt", params.pSalt, params.ulSaltLen));
122
23.8k
    PRINT_KEY(50, (NULL, "HKDF Extract: IKM2", ikm2));
123
124
23.8k
    prk = PK11_Derive(ikm2, CKM_HKDF_DERIVE, &paramsi, CKM_HKDF_DERIVE,
125
23.8k
                      CKA_DERIVE, 0);
126
23.8k
    PK11_FreeSymKey(newIkm2);
127
23.8k
    PK11_FreeSymKey(newIkm1);
128
23.8k
    if (slot)
129
10.6k
        PK11_FreeSlot(slot);
130
23.8k
    if (!prk) {
131
0
        return SECFailure;
132
0
    }
133
134
23.8k
    PRINT_KEY(50, (NULL, "HKDF Extract", prk));
135
23.8k
    *prkp = prk;
136
137
23.8k
    return SECSuccess;
138
23.8k
}
139
140
SECStatus
141
tls13_HkdfExpandLabelGeneral(CK_MECHANISM_TYPE deriveMech, PK11SymKey *prk,
142
                             SSLHashType baseHash,
143
                             const PRUint8 *handshakeHash, unsigned int handshakeHashLen,
144
                             const char *label, unsigned int labelLen,
145
                             CK_MECHANISM_TYPE algorithm, unsigned int keySize,
146
                             SSLProtocolVariant variant, PK11SymKey **keyp)
147
471k
{
148
471k
    CK_HKDF_PARAMS params;
149
471k
    SECItem paramsi = { siBuffer, NULL, 0 };
150
    /* Size of info array needs to be big enough to hold the maximum Prefix,
151
     * Label, plus HandshakeHash. If it's ever to small, the code will abort.
152
     */
153
471k
    PRUint8 info[256];
154
471k
    sslBuffer infoBuf = SSL_BUFFER(info);
155
471k
    PK11SymKey *derived;
156
471k
    SECStatus rv;
157
471k
    const char *kLabelPrefixTls = "tls13 ";
158
471k
    const char *kLabelPrefixDtls = "dtls13";
159
471k
    const unsigned int kLabelPrefixLen =
160
471k
        (variant == ssl_variant_stream) ? strlen(kLabelPrefixTls) : strlen(kLabelPrefixDtls);
161
471k
    const char *kLabelPrefix =
162
471k
        (variant == ssl_variant_stream) ? kLabelPrefixTls : kLabelPrefixDtls;
163
164
471k
    PORT_Assert(prk);
165
471k
    PORT_Assert(keyp);
166
471k
    if ((handshakeHashLen > 255) ||
167
471k
        (handshakeHash == NULL && handshakeHashLen > 0) ||
168
471k
        (labelLen + kLabelPrefixLen > 255)) {
169
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
170
0
        return SECFailure;
171
0
    }
172
173
    /*
174
     *  [draft-ietf-tls-tls13-11] Section 7.1:
175
     *
176
     *  HKDF-Expand-Label(Secret, Label, HashValue, Length) =
177
     *       HKDF-Expand(Secret, HkdfLabel, Length)
178
     *
179
     *  Where HkdfLabel is specified as:
180
     *
181
     *  struct HkdfLabel {
182
     *    uint16 length;
183
     *    opaque label<9..255>;
184
     *    opaque hash_value<0..255>;
185
     *  };
186
     *
187
     *  Where:
188
     *  - HkdfLabel.length is Length
189
     *  - HkdfLabel.hash_value is HashValue.
190
     *  - HkdfLabel.label is "TLS 1.3, " + Label
191
     *
192
     */
193
471k
    rv = sslBuffer_AppendNumber(&infoBuf, keySize, 2);
194
471k
    if (rv != SECSuccess) {
195
0
        return SECFailure;
196
0
    }
197
471k
    rv = sslBuffer_AppendNumber(&infoBuf, labelLen + kLabelPrefixLen, 1);
198
471k
    if (rv != SECSuccess) {
199
0
        return SECFailure;
200
0
    }
201
471k
    rv = sslBuffer_Append(&infoBuf, kLabelPrefix, kLabelPrefixLen);
202
471k
    if (rv != SECSuccess) {
203
0
        return SECFailure;
204
0
    }
205
471k
    rv = sslBuffer_Append(&infoBuf, label, labelLen);
206
471k
    if (rv != SECSuccess) {
207
0
        return SECFailure;
208
0
    }
209
471k
    rv = sslBuffer_AppendVariable(&infoBuf, handshakeHash, handshakeHashLen, 1);
210
471k
    if (rv != SECSuccess) {
211
0
        return SECFailure;
212
0
    }
213
214
471k
    params.bExtract = CK_FALSE;
215
471k
    params.bExpand = CK_TRUE;
216
471k
    params.prfHashMechanism = kTlsHkdfInfo[baseHash].pkcs11Mech;
217
471k
    params.pInfo = SSL_BUFFER_BASE(&infoBuf);
218
471k
    params.ulInfoLen = SSL_BUFFER_LEN(&infoBuf);
219
471k
    paramsi.data = (unsigned char *)&params;
220
471k
    paramsi.len = sizeof(params);
221
471k
    derived = PK11_DeriveWithFlags(prk, deriveMech,
222
471k
                                   &paramsi, algorithm,
223
471k
                                   CKA_DERIVE, keySize,
224
471k
                                   CKF_SIGN | CKF_VERIFY);
225
471k
    if (!derived) {
226
0
        return SECFailure;
227
0
    }
228
229
471k
    *keyp = derived;
230
231
471k
#ifdef TRACE
232
471k
    if (ssl_trace >= 50) {
233
        /* Make sure the label is null terminated. */
234
0
        char labelStr[100];
235
0
        PORT_Memcpy(labelStr, label, labelLen);
236
0
        labelStr[labelLen] = 0;
237
0
        SSL_TRC(50, ("HKDF Expand: label='tls13 %s',requested length=%d",
238
0
                     labelStr, keySize));
239
0
    }
240
471k
    PRINT_KEY(50, (NULL, "PRK", prk));
241
471k
    PRINT_BUF(50, (NULL, "Hash", handshakeHash, handshakeHashLen));
242
471k
    PRINT_BUF(50, (NULL, "Info", SSL_BUFFER_BASE(&infoBuf),
243
471k
                   SSL_BUFFER_LEN(&infoBuf)));
244
471k
    PRINT_KEY(50, (NULL, "Derived key", derived));
245
471k
#endif
246
247
471k
    return SECSuccess;
248
471k
}
249
250
SECStatus
251
tls13_HkdfExpandLabel(PK11SymKey *prk, SSLHashType baseHash,
252
                      const PRUint8 *handshakeHash, unsigned int handshakeHashLen,
253
                      const char *label, unsigned int labelLen,
254
                      CK_MECHANISM_TYPE algorithm, unsigned int keySize,
255
                      SSLProtocolVariant variant, PK11SymKey **keyp)
256
328k
{
257
328k
    return tls13_HkdfExpandLabelGeneral(CKM_HKDF_DERIVE, prk, baseHash,
258
328k
                                        handshakeHash, handshakeHashLen,
259
328k
                                        label, labelLen, algorithm, keySize,
260
328k
                                        variant, keyp);
261
328k
}
262
263
SECStatus
264
tls13_HkdfExpandLabelRaw(PK11SymKey *prk, SSLHashType baseHash,
265
                         const PRUint8 *handshakeHash, unsigned int handshakeHashLen,
266
                         const char *label, unsigned int labelLen,
267
                         SSLProtocolVariant variant, unsigned char *output,
268
                         unsigned int outputLen)
269
143k
{
270
143k
    PK11SymKey *derived = NULL;
271
143k
    SECItem *rawkey;
272
143k
    SECStatus rv;
273
274
    /* the result is not really a key, it's a data object */
275
143k
    rv = tls13_HkdfExpandLabelGeneral(CKM_HKDF_DATA, prk, baseHash,
276
143k
                                      handshakeHash, handshakeHashLen,
277
143k
                                      label, labelLen, CKM_HKDF_DERIVE, outputLen,
278
143k
                                      variant, &derived);
279
143k
    if (rv != SECSuccess || !derived) {
280
0
        goto abort;
281
0
    }
282
283
143k
    rv = PK11_ExtractKeyValue(derived);
284
143k
    if (rv != SECSuccess) {
285
0
        goto abort;
286
0
    }
287
288
143k
    rawkey = PK11_GetKeyData(derived);
289
143k
    if (!rawkey) {
290
0
        goto abort;
291
0
    }
292
293
143k
    PORT_Assert(rawkey->len == outputLen);
294
143k
    memcpy(output, rawkey->data, outputLen);
295
143k
    PK11_FreeSymKey(derived);
296
297
143k
    return SECSuccess;
298
299
0
abort:
300
0
    if (derived) {
301
0
        PK11_FreeSymKey(derived);
302
0
    }
303
0
    PORT_SetError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
304
0
    return SECFailure;
305
143k
}