Coverage Report

Created: 2026-05-19 06:33

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