Coverage Report

Created: 2025-12-20 07:02

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