Coverage Report

Created: 2026-10-13 06:23

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/nss/lib/ssl/tls13replay.c
Line
Count
Source
1
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
/*
3
 * Anti-replay measures for TLS 1.3.
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 "nss.h" /* for NSS_RegisterShutdown */
10
#include "pk11pub.h"
11
#include "prmon.h"
12
#include "prtime.h"
13
#include "secerr.h"
14
#include "ssl.h"
15
#include "sslbloom.h"
16
#include "sslimpl.h"
17
#include "tls13hkdf.h"
18
#include "tls13psk.h"
19
20
struct SSLAntiReplayContextStr {
21
    /* The number of outstanding references to this context. */
22
    PRInt32 refCount;
23
    /* Used to serialize access. */
24
    PRMonitor *lock;
25
    /* The filters, use of which alternates. */
26
    sslBloomFilter filters[2];
27
    /* Which of the two filters is active (0 or 1). */
28
    PRUint8 current;
29
    /* The time that we will next update. */
30
    PRTime nextUpdate;
31
    /* The width of the window; i.e., the period of updates. */
32
    PRTime window;
33
    /* This key ensures that the bloom filter index is unpredictable. */
34
    PK11SymKey *key;
35
};
36
37
void
38
tls13_ReleaseAntiReplayContext(SSLAntiReplayContext *ctx)
39
62.0k
{
40
62.0k
    if (!ctx) {
41
62.0k
        return;
42
62.0k
    }
43
0
    PRInt32 refCount = PR_ATOMIC_DECREMENT(&ctx->refCount);
44
0
    PORT_ReleaseAssert(refCount >= 0);
45
0
    if (refCount != 0) {
46
0
        return;
47
0
    }
48
49
0
    if (ctx->lock) {
50
0
        PR_DestroyMonitor(ctx->lock);
51
0
        ctx->lock = NULL;
52
0
    }
53
0
    PK11_FreeSymKey(ctx->key);
54
0
    ctx->key = NULL;
55
0
    sslBloom_Destroy(&ctx->filters[0]);
56
0
    sslBloom_Destroy(&ctx->filters[1]);
57
0
    PORT_Free(ctx);
58
0
}
59
60
/* Clear the current state and free any resources we allocated. */
61
SECStatus
62
SSLExp_ReleaseAntiReplayContext(SSLAntiReplayContext *ctx)
63
0
{
64
0
    tls13_ReleaseAntiReplayContext(ctx);
65
0
    return SECSuccess;
66
0
}
67
68
SSLAntiReplayContext *
69
tls13_RefAntiReplayContext(SSLAntiReplayContext *ctx)
70
0
{
71
0
    PORT_Assert(ctx);
72
0
    PRInt32 refCount = PR_ATOMIC_INCREMENT(&ctx->refCount);
73
0
    PORT_ReleaseAssert(refCount > 1);
74
0
    return ctx;
75
0
}
76
77
static SECStatus
78
tls13_AntiReplayKeyGen(SSLAntiReplayContext *ctx)
79
0
{
80
0
    PK11SlotInfo *slot;
81
82
0
    PORT_Assert(ctx);
83
84
0
    slot = PK11_GetBestSlot(CKM_HKDF_DERIVE, NULL);
85
0
    if (!slot) {
86
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
87
0
        return SECFailure;
88
0
    }
89
90
0
    ctx->key = PK11_KeyGen(slot, CKM_HKDF_KEY_GEN, NULL, 32, NULL);
91
0
    if (!ctx->key) {
92
0
        goto loser;
93
0
    }
94
95
0
    PK11_FreeSlot(slot);
96
0
    return SECSuccess;
97
98
0
loser:
99
0
    PK11_FreeSlot(slot);
100
0
    return SECFailure;
101
0
}
102
103
/* Set a limit on the combination of number of hashes and bits in each hash. */
104
0
#define SSL_MAX_BLOOM_FILTER_SIZE 64
105
106
/*
107
 * The context created by this function can be called concurrently on multiple
108
 * threads if the server is multi-threaded.  A monitor is used to ensure that
109
 * only one thread can access the structures that change over time, but no such
110
 * guarantee is provided for configuration data.
111
 */
112
SECStatus
113
SSLExp_CreateAntiReplayContext(PRTime now, PRTime window, unsigned int k,
114
                               unsigned int bits, SSLAntiReplayContext **pctx)
115
0
{
116
0
    SECStatus rv;
117
118
0
    if (window <= 0 || k == 0 || bits == 0 || pctx == NULL) {
119
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
120
0
        return SECFailure;
121
0
    }
122
0
    if ((k * (bits + 7) / 8) > SSL_MAX_BLOOM_FILTER_SIZE) {
123
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
124
0
        return SECFailure;
125
0
    }
126
127
0
    SSLAntiReplayContext *ctx = PORT_ZNew(SSLAntiReplayContext);
128
0
    if (!ctx) {
129
0
        return SECFailure; /* Code already set. */
130
0
    }
131
132
0
    ctx->refCount = 1;
133
0
    ctx->lock = PR_NewMonitor();
134
0
    if (!ctx->lock) {
135
0
        goto loser; /* Code already set. */
136
0
    }
137
138
0
    rv = tls13_AntiReplayKeyGen(ctx);
139
0
    if (rv != SECSuccess) {
140
0
        goto loser; /* Code already set. */
141
0
    }
142
143
0
    rv = sslBloom_Init(&ctx->filters[0], k, bits);
144
0
    if (rv != SECSuccess) {
145
0
        goto loser; /* Code already set. */
146
0
    }
147
0
    rv = sslBloom_Init(&ctx->filters[1], k, bits);
148
0
    if (rv != SECSuccess) {
149
0
        goto loser; /* Code already set. */
150
0
    }
151
    /* When starting out, ensure that 0-RTT is not accepted until the window is
152
     * updated.  A ClientHello might have been accepted prior to a restart. */
153
0
    sslBloom_Fill(&ctx->filters[1]);
154
155
0
    ctx->current = 0;
156
0
    ctx->nextUpdate = now + window;
157
0
    ctx->window = window;
158
0
    *pctx = ctx;
159
0
    return SECSuccess;
160
161
0
loser:
162
0
    tls13_ReleaseAntiReplayContext(ctx);
163
0
    return SECFailure;
164
0
}
165
166
SECStatus
167
SSLExp_SetAntiReplayContext(PRFileDesc *fd, SSLAntiReplayContext *ctx)
168
0
{
169
0
    sslSocket *ss = ssl_FindSocket(fd);
170
0
    if (!ss) {
171
0
        return SECFailure; /* Code already set. */
172
0
    }
173
0
    tls13_ReleaseAntiReplayContext(ss->antiReplay);
174
0
    if (ctx != NULL) {
175
0
        ss->antiReplay = tls13_RefAntiReplayContext(ctx);
176
0
    } else {
177
0
        ss->antiReplay = NULL;
178
0
    }
179
0
    return SECSuccess;
180
0
}
181
182
static void
183
tls13_AntiReplayUpdate(SSLAntiReplayContext *ctx, PRTime now)
184
0
{
185
0
    PR_ASSERT_CURRENT_THREAD_IN_MONITOR(ctx->lock);
186
0
    if (now >= ctx->nextUpdate) {
187
0
        ctx->current ^= 1;
188
0
        ctx->nextUpdate = now + ctx->window;
189
0
        sslBloom_Zero(ctx->filters + ctx->current);
190
0
    }
191
0
}
192
193
PRBool
194
tls13_InWindow(const sslSocket *ss, const sslSessionID *sid)
195
0
{
196
0
    PRInt32 timeDelta;
197
198
    /* Calculate the difference between the client's view of the age of the
199
     * ticket (in |ss->xtnData.ticketAge|) and the server's view, which we now
200
     * calculate.  The result should be close to zero.  timeDelta is signed to
201
     * make the comparisons below easier. */
202
0
    timeDelta = ss->xtnData.ticketAge -
203
0
                ((ssl_Time(ss) - sid->creationTime) / PR_USEC_PER_MSEC);
204
205
    /* Only allow the time delta to be at most half of our window.  This is
206
     * symmetrical, though it doesn't need to be; this assumes that clock errors
207
     * on server and client will tend to cancel each other out.
208
     *
209
     * There are two anti-replay filters that roll over each window.  In the
210
     * worst case, immediately after a rollover of the filters, we only have a
211
     * single window worth of recorded 0-RTT attempts.  Thus, the period in
212
     * which we can accept 0-RTT is at most one window wide.  This uses PR_ABS()
213
     * and half the window so that the first attempt can be up to half a window
214
     * early and then replays will be caught until the attempts are half a
215
     * window late.
216
     *
217
     * For example, a 0-RTT attempt arrives early, but near the end of window 1.
218
     * The attempt is then recorded in window 1.  Rollover to window 2 could
219
     * occur immediately afterwards.  Window 1 is still checked for new 0-RTT
220
     * attempts for the remainder of window 2.  Therefore, attempts to replay
221
     * are detected because the value is recorded in window 1.  When rollover
222
     * occurs again, window 1 is erased and window 3 instated.  If we allowed an
223
     * attempt to be late by more than half a window, then this check would not
224
     * prevent the same 0-RTT attempt from being accepted during window 1 and
225
     * later window 3.
226
     */
227
0
    PRInt32 allowance = ss->antiReplay->window / (PR_USEC_PER_MSEC * 2);
228
0
    SSL_TRC(10, ("%d: TLS13[%d]: replay check time delta=%d, allow=%d",
229
0
                 SSL_GETPID(), ss->fd, timeDelta, allowance));
230
0
    return PR_ABS(timeDelta) < allowance;
231
0
}
232
233
/* Checks for a duplicate in the two filters we have.  Performs maintenance on
234
 * the filters as a side-effect. This only detects a probable replay, it's
235
 * possible that this will return true when the 0-RTT attempt is not genuinely a
236
 * replay.  In that case, we reject 0-RTT unnecessarily, but that's OK because
237
 * no client expects 0-RTT to work every time. */
238
PRBool
239
tls13_IsReplay(const sslSocket *ss, const sslSessionID *sid)
240
0
{
241
0
    PRBool replay;
242
0
    unsigned int size;
243
0
    PRUint8 index;
244
0
    SECStatus rv;
245
0
    static const char *label = "anti-replay";
246
0
    PRUint8 buf[SSL_MAX_BLOOM_FILTER_SIZE];
247
0
    SSLAntiReplayContext *ctx = ss->antiReplay;
248
249
    /* If SSL_SetAntiReplayContext hasn't been called with a valid context, then
250
     * treat all attempts at 0-RTT as a replay. */
251
0
    if (ctx == NULL) {
252
0
        return PR_TRUE;
253
0
    }
254
255
0
    if (!sid) {
256
0
        PORT_Assert(ss->xtnData.selectedPsk->type == ssl_psk_external);
257
0
    } else if (!tls13_InWindow(ss, sid)) {
258
0
        return PR_TRUE;
259
0
    }
260
261
0
    size = ctx->filters[0].k * (ctx->filters[0].bits + 7) / 8;
262
0
    PORT_Assert(size <= SSL_MAX_BLOOM_FILTER_SIZE);
263
0
    rv = tls13_HkdfExpandLabelRaw(ctx->key, ssl_hash_sha256,
264
0
                                  ss->xtnData.pskBinder.data,
265
0
                                  ss->xtnData.pskBinder.len,
266
0
                                  label, strlen(label),
267
0
                                  ss->protocolVariant, buf, size);
268
0
    if (rv != SECSuccess) {
269
0
        return PR_TRUE;
270
0
    }
271
272
0
    PR_EnterMonitor(ctx->lock);
273
0
    tls13_AntiReplayUpdate(ctx, ssl_Time(ss));
274
275
0
    index = ctx->current;
276
0
    replay = sslBloom_Add(&ctx->filters[index], buf);
277
0
    SSL_TRC(10, ("%d: TLS13[%d]: replay check current window: %s",
278
0
                 SSL_GETPID(), ss->fd, replay ? "replay" : "ok"));
279
0
    if (!replay) {
280
0
        replay = sslBloom_Check(&ctx->filters[index ^ 1], buf);
281
0
        SSL_TRC(10, ("%d: TLS13[%d]: replay check previous window: %s",
282
0
                     SSL_GETPID(), ss->fd, replay ? "replay" : "ok"));
283
0
    }
284
285
0
    PR_ExitMonitor(ctx->lock);
286
0
    return replay;
287
0
}