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
tls13_ReleaseAntiReplayContext(SSLAntiReplayContext * ctx)39 tls13_ReleaseAntiReplayContext(SSLAntiReplayContext *ctx)
40 {
41     if (!ctx) {
42         return;
43     }
44     if (PR_ATOMIC_DECREMENT(&ctx->refCount) >= 1) {
45         return;
46     }
47 
48     if (ctx->lock) {
49         PZ_DestroyMonitor(ctx->lock);
50         ctx->lock = NULL;
51     }
52     PK11_FreeSymKey(ctx->key);
53     ctx->key = NULL;
54     sslBloom_Destroy(&ctx->filters[0]);
55     sslBloom_Destroy(&ctx->filters[1]);
56     PORT_Free(ctx);
57 }
58 
59 /* Clear the current state and free any resources we allocated. */
60 SECStatus
SSLExp_ReleaseAntiReplayContext(SSLAntiReplayContext * ctx)61 SSLExp_ReleaseAntiReplayContext(SSLAntiReplayContext *ctx)
62 {
63     tls13_ReleaseAntiReplayContext(ctx);
64     return SECSuccess;
65 }
66 
67 SSLAntiReplayContext *
tls13_RefAntiReplayContext(SSLAntiReplayContext * ctx)68 tls13_RefAntiReplayContext(SSLAntiReplayContext *ctx)
69 {
70     PORT_Assert(ctx);
71     PR_ATOMIC_INCREMENT(&ctx->refCount);
72     return ctx;
73 }
74 
75 static SECStatus
tls13_AntiReplayKeyGen(SSLAntiReplayContext * ctx)76 tls13_AntiReplayKeyGen(SSLAntiReplayContext *ctx)
77 {
78     PK11SlotInfo *slot;
79 
80     PORT_Assert(ctx);
81 
82     slot = PK11_GetBestSlot(CKM_HKDF_DERIVE, NULL);
83     if (!slot) {
84         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
85         return SECFailure;
86     }
87 
88     ctx->key = PK11_KeyGen(slot, CKM_HKDF_KEY_GEN, NULL, 32, NULL);
89     if (!ctx->key) {
90         goto loser;
91     }
92 
93     PK11_FreeSlot(slot);
94     return SECSuccess;
95 
96 loser:
97     PK11_FreeSlot(slot);
98     return SECFailure;
99 }
100 
101 /* Set a limit on the combination of number of hashes and bits in each hash. */
102 #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
SSLExp_CreateAntiReplayContext(PRTime now,PRTime window,unsigned int k,unsigned int bits,SSLAntiReplayContext ** pctx)111 SSLExp_CreateAntiReplayContext(PRTime now, PRTime window, unsigned int k,
112                                unsigned int bits, SSLAntiReplayContext **pctx)
113 {
114     SECStatus rv;
115 
116     if (window <= 0 || k == 0 || bits == 0 || pctx == NULL) {
117         PORT_SetError(SEC_ERROR_INVALID_ARGS);
118         return SECFailure;
119     }
120     if ((k * (bits + 7) / 8) > SSL_MAX_BLOOM_FILTER_SIZE) {
121         PORT_SetError(SEC_ERROR_INVALID_ARGS);
122         return SECFailure;
123     }
124 
125     SSLAntiReplayContext *ctx = PORT_ZNew(SSLAntiReplayContext);
126     if (!ctx) {
127         return SECFailure; /* Code already set. */
128     }
129 
130     ctx->refCount = 1;
131     ctx->lock = PZ_NewMonitor(nssILockSSL);
132     if (!ctx->lock) {
133         goto loser; /* Code already set. */
134     }
135 
136     rv = tls13_AntiReplayKeyGen(ctx);
137     if (rv != SECSuccess) {
138         goto loser; /* Code already set. */
139     }
140 
141     rv = sslBloom_Init(&ctx->filters[0], k, bits);
142     if (rv != SECSuccess) {
143         goto loser; /* Code already set. */
144     }
145     rv = sslBloom_Init(&ctx->filters[1], k, bits);
146     if (rv != SECSuccess) {
147         goto loser; /* Code already set. */
148     }
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     sslBloom_Fill(&ctx->filters[1]);
152 
153     ctx->current = 0;
154     ctx->nextUpdate = now + window;
155     ctx->window = window;
156     *pctx = ctx;
157     return SECSuccess;
158 
159 loser:
160     tls13_ReleaseAntiReplayContext(ctx);
161     return SECFailure;
162 }
163 
164 SECStatus
SSLExp_SetAntiReplayContext(PRFileDesc * fd,SSLAntiReplayContext * ctx)165 SSLExp_SetAntiReplayContext(PRFileDesc *fd, SSLAntiReplayContext *ctx)
166 {
167     sslSocket *ss = ssl_FindSocket(fd);
168     if (!ss) {
169         return SECFailure; /* Code already set. */
170     }
171     tls13_ReleaseAntiReplayContext(ss->antiReplay);
172     if (ctx != NULL) {
173         ss->antiReplay = tls13_RefAntiReplayContext(ctx);
174     } else {
175         ss->antiReplay = NULL;
176     }
177     return SECSuccess;
178 }
179 
180 static void
tls13_AntiReplayUpdate(SSLAntiReplayContext * ctx,PRTime now)181 tls13_AntiReplayUpdate(SSLAntiReplayContext *ctx, PRTime now)
182 {
183     PR_ASSERT_CURRENT_THREAD_IN_MONITOR(ctx->lock);
184     if (now >= ctx->nextUpdate) {
185         ctx->current ^= 1;
186         ctx->nextUpdate = now + ctx->window;
187         sslBloom_Zero(ctx->filters + ctx->current);
188     }
189 }
190 
191 PRBool
tls13_InWindow(const sslSocket * ss,const sslSessionID * sid)192 tls13_InWindow(const sslSocket *ss, const sslSessionID *sid)
193 {
194     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     timeDelta = ss->xtnData.ticketAge -
201                 ((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     PRInt32 allowance = ss->antiReplay->window / (PR_USEC_PER_MSEC * 2);
226     SSL_TRC(10, ("%d: TLS13[%d]: replay check time delta=%d, allow=%d",
227                  SSL_GETPID(), ss->fd, timeDelta, allowance));
228     return PR_ABS(timeDelta) < allowance;
229 }
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
tls13_IsReplay(const sslSocket * ss,const sslSessionID * sid)237 tls13_IsReplay(const sslSocket *ss, const sslSessionID *sid)
238 {
239     PRBool replay;
240     unsigned int size;
241     PRUint8 index;
242     SECStatus rv;
243     static const char *label = "anti-replay";
244     PRUint8 buf[SSL_MAX_BLOOM_FILTER_SIZE];
245     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     if (ctx == NULL) {
250         return PR_TRUE;
251     }
252 
253     if (!sid) {
254         PORT_Assert(ss->xtnData.selectedPsk->type == ssl_psk_external);
255     } else if (!tls13_InWindow(ss, sid)) {
256         return PR_TRUE;
257     }
258 
259     size = ctx->filters[0].k * (ctx->filters[0].bits + 7) / 8;
260     PORT_Assert(size <= SSL_MAX_BLOOM_FILTER_SIZE);
261     rv = tls13_HkdfExpandLabelRaw(ctx->key, ssl_hash_sha256,
262                                   ss->xtnData.pskBinder.data,
263                                   ss->xtnData.pskBinder.len,
264                                   label, strlen(label),
265                                   ss->protocolVariant, buf, size);
266     if (rv != SECSuccess) {
267         return PR_TRUE;
268     }
269 
270     PZ_EnterMonitor(ctx->lock);
271     tls13_AntiReplayUpdate(ctx, ssl_Time(ss));
272 
273     index = ctx->current;
274     replay = sslBloom_Add(&ctx->filters[index], buf);
275     SSL_TRC(10, ("%d: TLS13[%d]: replay check current window: %s",
276                  SSL_GETPID(), ss->fd, replay ? "replay" : "ok"));
277     if (!replay) {
278         replay = sslBloom_Check(&ctx->filters[index ^ 1], buf);
279         SSL_TRC(10, ("%d: TLS13[%d]: replay check previous window: %s",
280                      SSL_GETPID(), ss->fd, replay ? "replay" : "ok"));
281     }
282 
283     PZ_ExitMonitor(ctx->lock);
284     return replay;
285 }
286