Coverage Report

Created: 2025-12-20 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/nss/lib/ssl/dtlscon.c
Line
Count
Source
1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
/* This Source Code Form is subject to the terms of the Mozilla Public
3
 * License, v. 2.0. If a copy of the MPL was not distributed with this
4
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6
/*
7
 * DTLS Protocol
8
 */
9
10
#include "ssl.h"
11
#include "sslimpl.h"
12
#include "sslproto.h"
13
#include "dtls13con.h"
14
15
#ifndef PR_ARRAY_SIZE
16
#define PR_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
17
#endif
18
19
static SECStatus dtls_StartRetransmitTimer(sslSocket *ss);
20
static void dtls_RetransmitTimerExpiredCb(sslSocket *ss);
21
static SECStatus dtls_SendSavedWriteData(sslSocket *ss);
22
static void dtls_FinishedTimerCb(sslSocket *ss);
23
static void dtls_CancelAllTimers(sslSocket *ss);
24
25
/* -28 adjusts for the IP/UDP header */
26
static const PRUint16 COMMON_MTU_VALUES[] = {
27
    1500 - 28, /* Ethernet MTU */
28
    1280 - 28, /* IPv6 minimum MTU */
29
    576 - 28,  /* Common assumption */
30
    256 - 28   /* We're in serious trouble now */
31
};
32
33
618
#define DTLS_COOKIE_BYTES 32
34
/* Maximum DTLS expansion = header + IV + max CBC padding +
35
 * maximum MAC. */
36
126k
#define DTLS_MAX_EXPANSION (DTLS_RECORD_HEADER_LENGTH + 16 + 16 + 32)
37
38
/* List copied from ssl3con.c:cipherSuites */
39
static const ssl3CipherSuite nonDTLSSuites[] = {
40
    TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
41
    TLS_ECDHE_RSA_WITH_RC4_128_SHA,
42
    TLS_DHE_DSS_WITH_RC4_128_SHA,
43
    TLS_ECDH_RSA_WITH_RC4_128_SHA,
44
    TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
45
    TLS_RSA_WITH_RC4_128_MD5,
46
    TLS_RSA_WITH_RC4_128_SHA,
47
    0 /* End of list marker */
48
};
49
50
/* Map back and forth between TLS and DTLS versions in wire format.
51
 * Mapping table is:
52
 *
53
 * TLS             DTLS
54
 * 1.1 (0302)      1.0 (feff)
55
 * 1.2 (0303)      1.2 (fefd)
56
 * 1.3 (0304)      1.3 (fefc)
57
 */
58
SSL3ProtocolVersion
59
dtls_TLSVersionToDTLSVersion(SSL3ProtocolVersion tlsv)
60
125k
{
61
125k
    if (tlsv == SSL_LIBRARY_VERSION_TLS_1_1) {
62
13.1k
        return SSL_LIBRARY_VERSION_DTLS_1_0_WIRE;
63
13.1k
    }
64
112k
    if (tlsv == SSL_LIBRARY_VERSION_TLS_1_2) {
65
93.3k
        return SSL_LIBRARY_VERSION_DTLS_1_2_WIRE;
66
93.3k
    }
67
19.0k
    if (tlsv == SSL_LIBRARY_VERSION_TLS_1_3) {
68
18.7k
        return SSL_LIBRARY_VERSION_DTLS_1_3_WIRE;
69
18.7k
    }
70
71
    /* Anything else is an error, so return
72
     * the invalid version 0xffff. */
73
327
    return 0xffff;
74
19.0k
}
75
76
/* Map known DTLS versions to known TLS versions.
77
 * - Invalid versions (< 1.0) return a version of 0
78
 * - Versions > known return a version one higher than we know of
79
 * to accomodate a theoretically newer version */
80
SSL3ProtocolVersion
81
dtls_DTLSVersionToTLSVersion(SSL3ProtocolVersion dtlsv)
82
36.5k
{
83
36.5k
    if (MSB(dtlsv) == 0xff) {
84
421
        return 0;
85
421
    }
86
87
36.1k
    if (dtlsv == SSL_LIBRARY_VERSION_DTLS_1_0_WIRE) {
88
1.49k
        return SSL_LIBRARY_VERSION_TLS_1_1;
89
1.49k
    }
90
    /* Handle the skipped version of DTLS 1.1 by returning
91
     * an error. */
92
34.6k
    if (dtlsv == ((~0x0101) & 0xffff)) {
93
22
        return 0;
94
22
    }
95
34.6k
    if (dtlsv == SSL_LIBRARY_VERSION_DTLS_1_2_WIRE) {
96
22.2k
        return SSL_LIBRARY_VERSION_TLS_1_2;
97
22.2k
    }
98
12.3k
    if (dtlsv == SSL_LIBRARY_VERSION_DTLS_1_3_WIRE) {
99
5.13k
        return SSL_LIBRARY_VERSION_TLS_1_3;
100
5.13k
    }
101
102
    /* Return a fictional higher version than we know of */
103
7.23k
    return SSL_LIBRARY_VERSION_MAX_SUPPORTED + 1;
104
12.3k
}
105
106
/* On this socket, Disable non-DTLS cipher suites in the argument's list */
107
SECStatus
108
ssl3_DisableNonDTLSSuites(sslSocket *ss)
109
29.4k
{
110
29.4k
    const ssl3CipherSuite *suite;
111
112
235k
    for (suite = nonDTLSSuites; *suite; ++suite) {
113
206k
        PORT_CheckSuccess(ssl3_CipherPrefSet(ss, *suite, PR_FALSE));
114
206k
    }
115
29.4k
    return SECSuccess;
116
29.4k
}
117
118
/* Allocate a DTLSQueuedMessage.
119
 *
120
 * Called from dtls_QueueMessage()
121
 */
122
static DTLSQueuedMessage *
123
dtls_AllocQueuedMessage(ssl3CipherSpec *cwSpec, SSLContentType ct,
124
                        const unsigned char *data, PRUint32 len)
125
75.6k
{
126
75.6k
    DTLSQueuedMessage *msg;
127
128
75.6k
    msg = PORT_ZNew(DTLSQueuedMessage);
129
75.6k
    if (!msg)
130
0
        return NULL;
131
132
75.6k
    msg->data = PORT_Alloc(len);
133
75.6k
    if (!msg->data) {
134
0
        PORT_Free(msg);
135
0
        return NULL;
136
0
    }
137
75.6k
    PORT_Memcpy(msg->data, data, len);
138
139
75.6k
    msg->len = len;
140
75.6k
    msg->cwSpec = cwSpec;
141
75.6k
    msg->type = ct;
142
    /* Safe if we are < 1.3, since the refct is
143
     * already very high. */
144
75.6k
    ssl_CipherSpecAddRef(cwSpec);
145
146
75.6k
    return msg;
147
75.6k
}
148
149
/*
150
 * Free a handshake message
151
 *
152
 * Called from dtls_FreeHandshakeMessages()
153
 */
154
void
155
dtls_FreeHandshakeMessage(DTLSQueuedMessage *msg)
156
75.6k
{
157
75.6k
    if (!msg)
158
0
        return;
159
160
    /* Safe if we are < 1.3, since the refct is
161
     * already very high. */
162
75.6k
    ssl_CipherSpecRelease(msg->cwSpec);
163
75.6k
    PORT_ZFree(msg->data, msg->len);
164
75.6k
    PORT_Free(msg);
165
75.6k
}
166
167
/*
168
 * Free a list of handshake messages
169
 *
170
 * Called from:
171
 *              dtls_HandleHandshake()
172
 *              ssl3_DestroySSL3Info()
173
 */
174
void
175
dtls_FreeHandshakeMessages(PRCList *list)
176
75.1k
{
177
75.1k
    PRCList *cur_p;
178
179
150k
    while (!PR_CLIST_IS_EMPTY(list)) {
180
75.3k
        cur_p = PR_LIST_TAIL(list);
181
75.3k
        PR_REMOVE_LINK(cur_p);
182
75.3k
        dtls_FreeHandshakeMessage((DTLSQueuedMessage *)cur_p);
183
75.3k
    }
184
75.1k
}
185
186
/* Called by dtls_HandleHandshake() and dtls_MaybeRetransmitHandshake() if a
187
 * handshake message retransmission is detected. */
188
static SECStatus
189
dtls_RetransmitDetected(sslSocket *ss)
190
1.31k
{
191
1.31k
    dtlsTimer *rtTimer = ss->ssl3.hs.rtTimer;
192
1.31k
    dtlsTimer *hdTimer = ss->ssl3.hs.hdTimer;
193
1.31k
    SECStatus rv = SECSuccess;
194
195
1.31k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
196
1.31k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
197
198
1.31k
    if (rtTimer->cb == dtls_RetransmitTimerExpiredCb) {
199
        /* Check to see if we retransmitted recently. If so,
200
         * suppress the triggered retransmit. This avoids
201
         * retransmit wars after packet loss.
202
         * This is not in RFC 5346 but it should be.
203
         */
204
702
        if ((PR_IntervalNow() - rtTimer->started) >
205
702
            (rtTimer->timeout / 4)) {
206
10
            SSL_TRC(30,
207
10
                    ("%d: SSL3[%d]: Shortcutting retransmit timer",
208
10
                     SSL_GETPID(), ss->fd));
209
210
            /* Cancel the timer and call the CB,
211
             * which re-arms the timer */
212
10
            dtls_CancelTimer(ss, ss->ssl3.hs.rtTimer);
213
10
            dtls_RetransmitTimerExpiredCb(ss);
214
692
        } else {
215
692
            SSL_TRC(30,
216
692
                    ("%d: SSL3[%d]: Ignoring retransmission: "
217
692
                     "last retransmission %dms ago, suppressed for %dms",
218
692
                     SSL_GETPID(), ss->fd,
219
692
                     PR_IntervalNow() - rtTimer->started,
220
692
                     rtTimer->timeout / 4));
221
692
        }
222
702
    } else if (hdTimer->cb == dtls_FinishedTimerCb) {
223
184
        SSL_TRC(30, ("%d: SSL3[%d]: Retransmit detected in holddown",
224
184
                     SSL_GETPID(), ss->fd));
225
        /* Retransmit the messages and re-arm the timer
226
         * Note that we are not backing off the timer here.
227
         * The spec isn't clear and my reasoning is that this
228
         * may be a re-ordered packet rather than slowness,
229
         * so let's be aggressive. */
230
184
        dtls_CancelTimer(ss, ss->ssl3.hs.hdTimer);
231
184
        rv = dtls_TransmitMessageFlight(ss);
232
184
        if (rv == SECSuccess) {
233
184
            rv = dtls_StartHolddownTimer(ss);
234
184
        }
235
427
    } else {
236
        /* Otherwise handled in dtls13_HandleOutOfEpochRecord. */
237
427
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
238
381
            PORT_Assert(hdTimer->cb == NULL);
239
381
        }
240
241
427
        PORT_Assert(rtTimer->cb == NULL);
242
        /* ... and ignore it. */
243
427
    }
244
1.31k
    return rv;
245
1.31k
}
246
247
static SECStatus
248
dtls_HandleHandshakeMessage(sslSocket *ss, PRUint8 *data, PRBool last)
249
60.9k
{
250
60.9k
    ss->ssl3.hs.recvdHighWater = -1;
251
252
60.9k
    return ssl3_HandleHandshakeMessage(ss, data, ss->ssl3.hs.msg_len,
253
60.9k
                                       last);
254
60.9k
}
255
256
/* Called only from ssl3_HandleRecord, for each (deciphered) DTLS record.
257
 * origBuf is the decrypted ssl record content and is expected to contain
258
 * complete handshake records
259
 * Caller must hold the handshake and RecvBuf locks.
260
 *
261
 * Note that this code uses msg_len for two purposes:
262
 *
263
 * (1) To pass the length to ssl3_HandleHandshakeMessage()
264
 * (2) To carry the length of a message currently being reassembled
265
 *
266
 * However, unlike ssl3_HandleHandshake(), it is not used to carry
267
 * the state of reassembly (i.e., whether one is in progress). That
268
 * is carried in recvdHighWater and recvdFragments.
269
 */
270
336k
#define OFFSET_BYTE(o) (o / 8)
271
334k
#define OFFSET_MASK(o) (1 << (o % 8))
272
273
SECStatus
274
dtls_HandleHandshake(sslSocket *ss, DTLSEpoch epoch, sslSequenceNumber seqNum,
275
                     sslBuffer *origBuf)
276
79.2k
{
277
79.2k
    sslBuffer buf = *origBuf;
278
79.2k
    SECStatus rv = SECSuccess;
279
79.2k
    PRBool discarded = PR_FALSE;
280
281
79.2k
    ss->ssl3.hs.endOfFlight = PR_FALSE;
282
283
79.2k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
284
79.2k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
285
286
134k
    while (buf.len > 0) {
287
68.6k
        PRUint8 type;
288
68.6k
        PRUint32 message_length;
289
68.6k
        PRUint16 message_seq;
290
68.6k
        PRUint32 fragment_offset;
291
68.6k
        PRUint32 fragment_length;
292
68.6k
        PRUint32 offset;
293
294
68.6k
        if (buf.len < 12) {
295
173
            PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
296
173
            rv = SECFailure;
297
173
            goto loser;
298
173
        }
299
300
        /* Parse the header */
301
68.4k
        type = buf.buf[0];
302
68.4k
        message_length = (buf.buf[1] << 16) | (buf.buf[2] << 8) | buf.buf[3];
303
68.4k
        message_seq = (buf.buf[4] << 8) | buf.buf[5];
304
68.4k
        fragment_offset = (buf.buf[6] << 16) | (buf.buf[7] << 8) | buf.buf[8];
305
68.4k
        fragment_length = (buf.buf[9] << 16) | (buf.buf[10] << 8) | buf.buf[11];
306
307
68.4k
#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
308
68.4k
        if (message_length > MAX_HANDSHAKE_MSG_LEN) {
309
120
            (void)ssl3_DecodeError(ss);
310
120
            PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
311
120
            rv = SECFailure;
312
120
            goto loser;
313
120
        }
314
68.3k
#undef MAX_HANDSHAKE_MSG_LEN
315
316
68.3k
        buf.buf += 12;
317
68.3k
        buf.len -= 12;
318
319
        /* This fragment must be complete */
320
68.3k
        if (buf.len < fragment_length) {
321
151
            PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
322
151
            rv = SECFailure;
323
151
            goto loser;
324
151
        }
325
326
        /* Sanity check the packet contents */
327
68.2k
        if ((fragment_length + fragment_offset) > message_length) {
328
148
            PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
329
148
            rv = SECFailure;
330
148
            goto loser;
331
148
        }
332
333
        /* If we're a server and we receive what appears to be a retried
334
         * ClientHello, and we are expecting a ClientHello, move the receive
335
         * sequence number forward.  This allows for a retried ClientHello if we
336
         * send a stateless HelloRetryRequest. */
337
68.0k
        if (message_seq > ss->ssl3.hs.recvMessageSeq &&
338
1.85k
            message_seq == 1 &&
339
988
            fragment_offset == 0 &&
340
578
            ss->ssl3.hs.ws == wait_client_hello &&
341
371
            (SSLHandshakeType)type == ssl_hs_client_hello) {
342
140
            SSL_TRC(5, ("%d: DTLS[%d]: Received apparent 2nd ClientHello",
343
140
                        SSL_GETPID(), ss->fd));
344
140
            ss->ssl3.hs.recvMessageSeq = 1;
345
140
            ss->ssl3.hs.helloRetry = PR_TRUE;
346
140
        }
347
348
        /* There are three ways we could not be ready for this packet.
349
         *
350
         * 1. It's a partial next message.
351
         * 2. It's a partial or complete message beyond the next
352
         * 3. It's a message we've already seen
353
         *
354
         * If it's the complete next message we accept it right away.
355
         * This is the common case for short messages
356
         */
357
68.0k
        if ((message_seq == ss->ssl3.hs.recvMessageSeq) &&
358
65.0k
            (fragment_offset == 0) &&
359
61.9k
            (fragment_length == message_length)) {
360
            /* Complete next message. Process immediately */
361
60.2k
            ss->ssl3.hs.msg_type = (SSLHandshakeType)type;
362
60.2k
            ss->ssl3.hs.msg_len = message_length;
363
364
60.2k
            rv = dtls_HandleHandshakeMessage(ss, buf.buf,
365
60.2k
                                             buf.len == fragment_length);
366
60.2k
            if (rv != SECSuccess) {
367
11.0k
                goto loser;
368
11.0k
            }
369
60.2k
        } else {
370
7.85k
            if (message_seq < ss->ssl3.hs.recvMessageSeq) {
371
                /* Case 3: we do an immediate retransmit if we're
372
                 * in a waiting state. */
373
1.31k
                rv = dtls_RetransmitDetected(ss);
374
1.31k
                goto loser;
375
6.53k
            } else if (message_seq > ss->ssl3.hs.recvMessageSeq) {
376
                /* Case 2
377
                 *
378
                 * Ignore this message. This means we don't handle out of
379
                 * order complete messages that well, but we're still
380
                 * compliant and this probably does not happen often
381
                 *
382
                 * XXX OK for now. Maybe do something smarter at some point?
383
                 */
384
1.71k
                SSL_TRC(10, ("%d: SSL3[%d]: dtls_HandleHandshake, discarding handshake message",
385
1.71k
                             SSL_GETPID(), ss->fd));
386
1.71k
                discarded = PR_TRUE;
387
4.82k
            } else {
388
4.82k
                PRInt32 end = fragment_offset + fragment_length;
389
390
                /* Case 1
391
                 *
392
                 * Buffer the fragment for reassembly
393
                 */
394
                /* Make room for the message */
395
4.82k
                if (ss->ssl3.hs.recvdHighWater == -1) {
396
1.58k
                    PRUint32 map_length = OFFSET_BYTE(message_length) + 1;
397
398
1.58k
                    rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, message_length);
399
1.58k
                    if (rv != SECSuccess)
400
0
                        goto loser;
401
                    /* Make room for the fragment map */
402
1.58k
                    rv = sslBuffer_Grow(&ss->ssl3.hs.recvdFragments,
403
1.58k
                                        map_length);
404
1.58k
                    if (rv != SECSuccess)
405
0
                        goto loser;
406
407
                    /* Reset the reassembly map */
408
1.58k
                    ss->ssl3.hs.recvdHighWater = 0;
409
1.58k
                    PORT_Memset(ss->ssl3.hs.recvdFragments.buf, 0,
410
1.58k
                                ss->ssl3.hs.recvdFragments.space);
411
1.58k
                    ss->ssl3.hs.msg_type = (SSLHandshakeType)type;
412
1.58k
                    ss->ssl3.hs.msg_len = message_length;
413
1.58k
                }
414
415
                /* If we have a message length mismatch, abandon the reassembly
416
                 * in progress and hope that the next retransmit will give us
417
                 * something sane
418
                 */
419
4.82k
                if (message_length != ss->ssl3.hs.msg_len) {
420
134
                    ss->ssl3.hs.recvdHighWater = -1;
421
134
                    PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
422
134
                    rv = SECFailure;
423
134
                    goto loser;
424
134
                }
425
426
                /* Now copy this fragment into the buffer. */
427
4.69k
                if (end > ss->ssl3.hs.recvdHighWater) {
428
3.48k
                    PORT_Memcpy(ss->ssl3.hs.msg_body.buf + fragment_offset,
429
3.48k
                                buf.buf, fragment_length);
430
3.48k
                }
431
432
                /* This logic is a bit tricky. We have two values for
433
                 * reassembly state:
434
                 *
435
                 * - recvdHighWater contains the highest contiguous number of
436
                 *   bytes received
437
                 * - recvdFragments contains a bitmask of packets received
438
                 *   above recvdHighWater
439
                 *
440
                 * This avoids having to fill in the bitmask in the common
441
                 * case of adjacent fragments received in sequence
442
                 */
443
4.69k
                if (fragment_offset <= (unsigned int)ss->ssl3.hs.recvdHighWater) {
444
                    /* Either this is the adjacent fragment or an overlapping
445
                     * fragment */
446
2.53k
                    if (end > ss->ssl3.hs.recvdHighWater) {
447
1.33k
                        ss->ssl3.hs.recvdHighWater = end;
448
1.33k
                    }
449
2.53k
                } else {
450
188k
                    for (offset = fragment_offset; offset < end; offset++) {
451
186k
                        ss->ssl3.hs.recvdFragments.buf[OFFSET_BYTE(offset)] |=
452
186k
                            OFFSET_MASK(offset);
453
186k
                    }
454
2.15k
                }
455
456
                /* Now figure out the new high water mark if appropriate */
457
4.69k
                for (offset = ss->ssl3.hs.recvdHighWater;
458
148k
                     offset < ss->ssl3.hs.msg_len; offset++) {
459
                    /* Note that this loop is not efficient, since it counts
460
                     * bit by bit. If we have a lot of out-of-order packets,
461
                     * we should optimize this */
462
148k
                    if (ss->ssl3.hs.recvdFragments.buf[OFFSET_BYTE(offset)] &
463
148k
                        OFFSET_MASK(offset)) {
464
144k
                        ss->ssl3.hs.recvdHighWater++;
465
144k
                    } else {
466
3.96k
                        break;
467
3.96k
                    }
468
148k
                }
469
470
                /* If we have all the bytes, then we are good to go */
471
4.69k
                if (ss->ssl3.hs.recvdHighWater == ss->ssl3.hs.msg_len) {
472
729
                    rv = dtls_HandleHandshakeMessage(ss, ss->ssl3.hs.msg_body.buf,
473
729
                                                     buf.len == fragment_length);
474
475
729
                    if (rv != SECSuccess) {
476
128
                        goto loser;
477
128
                    }
478
729
                }
479
4.69k
            }
480
7.85k
        }
481
482
55.4k
        buf.buf += fragment_length;
483
55.4k
        buf.len -= fragment_length;
484
55.4k
    }
485
486
    // This should never happen, but belt and suspenders.
487
66.0k
    if (rv != SECSuccess) {
488
0
        PORT_Assert(0);
489
0
        goto loser;
490
0
    }
491
492
    /* If we processed all the fragments in this message, then mark it as remembered.
493
     * TODO(ekr@rtfm.com): Store out of order messages for DTLS 1.3 so ACKs work
494
     * better. Bug 1392620.*/
495
66.0k
    if (!discarded && tls13_MaybeTls13(ss)) {
496
11.9k
        rv = dtls13_RememberFragment(ss, &ss->ssl3.hs.dtlsRcvdHandshake,
497
11.9k
                                     0, 0, 0, epoch, seqNum);
498
11.9k
    }
499
66.0k
    if (rv != SECSuccess) {
500
0
        goto loser;
501
0
    }
502
66.0k
    rv = dtls13_SetupAcks(ss);
503
504
79.2k
loser:
505
79.2k
    origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
506
79.2k
    return rv;
507
66.0k
}
508
509
/* Enqueue a message (either handshake or CCS)
510
 *
511
 * Called from:
512
 *              dtls_StageHandshakeMessage()
513
 *              ssl3_SendChangeCipherSpecs()
514
 */
515
SECStatus
516
dtls_QueueMessage(sslSocket *ss, SSLContentType ct,
517
                  const PRUint8 *pIn, PRInt32 nIn)
518
75.6k
{
519
75.6k
    SECStatus rv = SECSuccess;
520
75.6k
    DTLSQueuedMessage *msg = NULL;
521
75.6k
    ssl3CipherSpec *spec;
522
523
75.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
524
75.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
525
526
75.6k
    spec = ss->ssl3.cwSpec;
527
75.6k
    msg = dtls_AllocQueuedMessage(spec, ct, pIn, nIn);
528
529
75.6k
    if (!msg) {
530
0
        PORT_SetError(SEC_ERROR_NO_MEMORY);
531
0
        rv = SECFailure;
532
75.6k
    } else {
533
75.6k
        PR_APPEND_LINK(&msg->link, &ss->ssl3.hs.lastMessageFlight);
534
75.6k
    }
535
536
75.6k
    return rv;
537
75.6k
}
538
539
/* Add DTLS handshake message to the pending queue
540
 * Empty the sendBuf buffer.
541
 * Always set sendBuf.len to 0, even when returning SECFailure.
542
 *
543
 * Called from:
544
 *              ssl3_AppendHandshakeHeader()
545
 *              dtls_FlushHandshake()
546
 */
547
SECStatus
548
dtls_StageHandshakeMessage(sslSocket *ss)
549
125k
{
550
125k
    SECStatus rv = SECSuccess;
551
552
125k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
553
125k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
554
555
    /* This function is sometimes called when no data is actually to
556
     * be staged, so just return SECSuccess. */
557
125k
    if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
558
53.6k
        return rv;
559
560
72.3k
    rv = dtls_QueueMessage(ss, ssl_ct_handshake,
561
72.3k
                           ss->sec.ci.sendBuf.buf, ss->sec.ci.sendBuf.len);
562
563
    /* Whether we succeeded or failed, toss the old handshake data. */
564
72.3k
    ss->sec.ci.sendBuf.len = 0;
565
72.3k
    return rv;
566
125k
}
567
568
/* Enqueue the handshake message in sendBuf (if any) and then
569
 * transmit the resulting flight of handshake messages.
570
 *
571
 * Called from:
572
 *              ssl3_FlushHandshake()
573
 */
574
SECStatus
575
dtls_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
576
53.6k
{
577
53.6k
    SECStatus rv = SECSuccess;
578
579
53.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
580
53.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
581
582
53.6k
    rv = dtls_StageHandshakeMessage(ss);
583
53.6k
    if (rv != SECSuccess) {
584
0
        return rv;
585
0
    }
586
587
53.6k
    if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
588
32.3k
        rv = dtls_TransmitMessageFlight(ss);
589
32.3k
        if (rv != SECSuccess) {
590
0
            return rv;
591
0
        }
592
593
32.3k
        if (!(flags & ssl_SEND_FLAG_NO_RETRANSMIT)) {
594
32.1k
            rv = dtls_StartRetransmitTimer(ss);
595
32.1k
        } else {
596
200
            PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
597
200
        }
598
32.3k
    }
599
600
53.6k
    return rv;
601
53.6k
}
602
603
/* The callback for when the retransmit timer expires
604
 *
605
 * Called from:
606
 *              dtls_CheckTimer()
607
 *              dtls_HandleHandshake()
608
 */
609
static void
610
dtls_RetransmitTimerExpiredCb(sslSocket *ss)
611
38
{
612
38
    SECStatus rv;
613
38
    dtlsTimer *timer = ss->ssl3.hs.rtTimer;
614
38
    ss->ssl3.hs.rtRetries++;
615
616
38
    if (!(ss->ssl3.hs.rtRetries % 3)) {
617
        /* If one of the messages was potentially greater than > MTU,
618
         * then downgrade. Do this every time we have retransmitted a
619
         * message twice, per RFC 9147 Sec. 4.4 */
620
0
        dtls_SetMTU(ss, ss->ssl3.hs.maxMessageSent - 1);
621
0
    }
622
623
38
    rv = dtls_TransmitMessageFlight(ss);
624
38
    if (rv == SECSuccess) {
625
        /* Re-arm the timer */
626
38
        timer->timeout *= 2;
627
38
        if (timer->timeout > DTLS_RETRANSMIT_MAX_MS) {
628
0
            timer->timeout = DTLS_RETRANSMIT_MAX_MS;
629
0
        }
630
631
38
        timer->started = PR_IntervalNow();
632
38
        timer->cb = dtls_RetransmitTimerExpiredCb;
633
634
38
        SSL_TRC(30,
635
38
                ("%d: SSL3[%d]: Retransmit #%d, next in %d",
636
38
                 SSL_GETPID(), ss->fd,
637
38
                 ss->ssl3.hs.rtRetries, timer->timeout));
638
38
    }
639
    /* else: OK for now. In future maybe signal the stack that we couldn't
640
     * transmit. For now, let the read handle any real network errors */
641
38
}
642
643
533k
#define DTLS_HS_HDR_LEN 12
644
126k
#define DTLS_MIN_FRAGMENT (DTLS_HS_HDR_LEN + 1 + DTLS_MAX_EXPANSION)
645
646
/* Encrypt and encode a handshake message fragment.  Flush the data out to the
647
 * network if there is insufficient space for any fragment. */
648
static SECStatus
649
dtls_SendFragment(sslSocket *ss, DTLSQueuedMessage *msg, PRUint8 *data,
650
                  unsigned int len)
651
126k
{
652
126k
    PRInt32 sent;
653
126k
    SECStatus rv;
654
655
126k
    PRINT_BUF(40, (ss, "dtls_SendFragment", data, len));
656
126k
    sent = ssl3_SendRecord(ss, msg->cwSpec, msg->type, data, len,
657
126k
                           ssl_SEND_FLAG_FORCE_INTO_BUFFER);
658
126k
    if (sent != len) {
659
0
        if (sent != -1) {
660
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
661
0
        }
662
0
        return SECFailure;
663
0
    }
664
665
    /* If another fragment won't fit, flush. */
666
126k
    if (ss->ssl3.mtu < ss->pendingBuf.len + DTLS_MIN_FRAGMENT) {
667
16.1k
        SSL_TRC(20, ("%d: DTLS[%d]: dtls_SendFragment: flush",
668
16.1k
                     SSL_GETPID(), ss->fd));
669
16.1k
        rv = dtls_SendSavedWriteData(ss);
670
16.1k
        if (rv != SECSuccess) {
671
0
            return SECFailure;
672
0
        }
673
16.1k
    }
674
126k
    return SECSuccess;
675
126k
}
676
677
/* Fragment a handshake message into multiple records and send them. */
678
static SECStatus
679
dtls_FragmentHandshake(sslSocket *ss, DTLSQueuedMessage *msg)
680
80.5k
{
681
80.5k
    PRBool fragmentWritten = PR_FALSE;
682
80.5k
    PRUint16 msgSeq;
683
80.5k
    PRUint8 *fragment;
684
80.5k
    PRUint32 fragmentOffset = 0;
685
80.5k
    PRUint32 fragmentLen;
686
80.5k
    const PRUint8 *content = msg->data + DTLS_HS_HDR_LEN;
687
80.5k
    PRUint32 contentLen = msg->len - DTLS_HS_HDR_LEN;
688
80.5k
    SECStatus rv;
689
690
    /* The headers consume 12 bytes so the smallest possible message (i.e., an
691
     * empty one) is 12 bytes. */
692
80.5k
    PORT_Assert(msg->len >= DTLS_HS_HDR_LEN);
693
694
    /* DTLS only supports fragmenting handshaking messages. */
695
80.5k
    PORT_Assert(msg->type == ssl_ct_handshake);
696
697
80.5k
    msgSeq = (msg->data[4] << 8) | msg->data[5];
698
699
    /* do {} while() so that empty messages are sent at least once. */
700
123k
    do {
701
123k
        PRUint8 buf[DTLS_MAX_MTU]; /* >= than largest plausible MTU */
702
123k
        PRBool hasUnackedRange;
703
123k
        PRUint32 end;
704
705
123k
        hasUnackedRange = dtls_NextUnackedRange(ss, msgSeq,
706
123k
                                                fragmentOffset, contentLen,
707
123k
                                                &fragmentOffset, &end);
708
123k
        if (!hasUnackedRange) {
709
467
            SSL_TRC(20, ("%d: SSL3[%d]: FragmentHandshake %d: all acknowledged",
710
467
                         SSL_GETPID(), ss->fd, msgSeq));
711
467
            break;
712
467
        }
713
714
122k
        SSL_TRC(20, ("%d: SSL3[%d]: FragmentHandshake %d: unacked=%u-%u",
715
122k
                     SSL_GETPID(), ss->fd, msgSeq, fragmentOffset, end));
716
717
        /* Cut down to the data we have available. */
718
122k
        PORT_Assert(fragmentOffset <= contentLen);
719
122k
        PORT_Assert(fragmentOffset <= end);
720
122k
        PORT_Assert(end <= contentLen);
721
122k
        fragmentLen = PR_MIN(end, contentLen) - fragmentOffset;
722
723
        /* Limit further by the record size limit.  Account for the header. */
724
122k
        fragmentLen = PR_MIN(fragmentLen,
725
122k
                             msg->cwSpec->recordSizeLimit - DTLS_HS_HDR_LEN);
726
727
        /* Reduce to the space remaining in the MTU. */
728
122k
        fragmentLen = PR_MIN(fragmentLen,
729
122k
                             ss->ssl3.mtu -           /* MTU estimate. */
730
122k
                                 ss->pendingBuf.len - /* Less any unsent records. */
731
122k
                                 DTLS_MAX_EXPANSION - /* Allow for expansion. */
732
122k
                                 DTLS_HS_HDR_LEN);    /* And the handshake header. */
733
122k
        PORT_Assert(fragmentLen > 0 || fragmentOffset == 0);
734
735
        /* Make totally sure that we will fit in the buffer. This should be
736
         * impossible; DTLS_MAX_MTU should always be more than ss->ssl3.mtu. */
737
122k
        if (fragmentLen >= (DTLS_MAX_MTU - DTLS_HS_HDR_LEN)) {
738
0
            PORT_Assert(0);
739
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
740
0
            return SECFailure;
741
0
        }
742
743
122k
        if (fragmentLen == contentLen) {
744
63.3k
            fragment = msg->data;
745
63.3k
        } else {
746
59.5k
            sslBuffer tmp = SSL_BUFFER_FIXED(buf, sizeof(buf));
747
748
            /* Construct an appropriate-sized fragment */
749
            /* Type, length, sequence */
750
59.5k
            rv = sslBuffer_Append(&tmp, msg->data, 6);
751
59.5k
            if (rv != SECSuccess) {
752
0
                return SECFailure;
753
0
            }
754
            /* Offset. */
755
59.5k
            rv = sslBuffer_AppendNumber(&tmp, fragmentOffset, 3);
756
59.5k
            if (rv != SECSuccess) {
757
0
                return SECFailure;
758
0
            }
759
            /* Length. */
760
59.5k
            rv = sslBuffer_AppendNumber(&tmp, fragmentLen, 3);
761
59.5k
            if (rv != SECSuccess) {
762
0
                return SECFailure;
763
0
            }
764
            /* Data. */
765
59.5k
            rv = sslBuffer_Append(&tmp, content + fragmentOffset, fragmentLen);
766
59.5k
            if (rv != SECSuccess) {
767
0
                return SECFailure;
768
0
            }
769
770
59.5k
            fragment = SSL_BUFFER_BASE(&tmp);
771
59.5k
        }
772
773
        /* Record that we are sending first, because encrypting
774
         * increments the sequence number. */
775
122k
        rv = dtls13_RememberFragment(ss, &ss->ssl3.hs.dtlsSentHandshake,
776
122k
                                     msgSeq, fragmentOffset, fragmentLen,
777
122k
                                     msg->cwSpec->epoch,
778
122k
                                     msg->cwSpec->nextSeqNum);
779
122k
        if (rv != SECSuccess) {
780
0
            return SECFailure;
781
0
        }
782
783
122k
        rv = dtls_SendFragment(ss, msg, fragment,
784
122k
                               fragmentLen + DTLS_HS_HDR_LEN);
785
122k
        if (rv != SECSuccess) {
786
0
            return SECFailure;
787
0
        }
788
789
122k
        fragmentWritten = PR_TRUE;
790
122k
        fragmentOffset += fragmentLen;
791
122k
    } while (fragmentOffset < contentLen);
792
793
80.5k
    if (!fragmentWritten) {
794
        /* Nothing was written if we got here, so the whole message must have
795
         * been acknowledged.  Discard it. */
796
250
        SSL_TRC(10, ("%d: SSL3[%d]: FragmentHandshake %d: removed",
797
250
                     SSL_GETPID(), ss->fd, msgSeq));
798
250
        PR_REMOVE_LINK(&msg->link);
799
250
        dtls_FreeHandshakeMessage(msg);
800
250
    }
801
802
80.5k
    return SECSuccess;
803
80.5k
}
804
805
/* Transmit a flight of handshake messages, stuffing them
806
 * into as few records as seems reasonable.
807
 *
808
 * TODO: Space separate UDP packets out a little.
809
 *
810
 * Called from:
811
 *             dtls_FlushHandshake()
812
 *             dtls_RetransmitTimerExpiredCb()
813
 */
814
SECStatus
815
dtls_TransmitMessageFlight(sslSocket *ss)
816
35.4k
{
817
35.4k
    SECStatus rv = SECSuccess;
818
35.4k
    PRCList *msg_p;
819
820
35.4k
    SSL_TRC(10, ("%d: SSL3[%d]: dtls_TransmitMessageFlight",
821
35.4k
                 SSL_GETPID(), ss->fd));
822
823
35.4k
    ssl_GetXmitBufLock(ss);
824
35.4k
    ssl_GetSpecReadLock(ss);
825
826
    /* DTLS does not buffer its handshake messages in ss->pendingBuf, but rather
827
     * in the lastMessageFlight structure. This is just a sanity check that some
828
     * programming error hasn't inadvertantly stuffed something in
829
     * ss->pendingBuf.  This function uses ss->pendingBuf temporarily and it
830
     * needs to be empty to start.
831
     */
832
35.4k
    PORT_Assert(!ss->pendingBuf.len);
833
834
35.4k
    for (msg_p = PR_LIST_HEAD(&ss->ssl3.hs.lastMessageFlight);
835
119k
         msg_p != &ss->ssl3.hs.lastMessageFlight;) {
836
84.1k
        DTLSQueuedMessage *msg = (DTLSQueuedMessage *)msg_p;
837
838
        /* Move the pointer forward so that the functions below are free to
839
         * remove messages from the list. */
840
84.1k
        msg_p = PR_NEXT_LINK(msg_p);
841
842
        /* Note: This function fragments messages so that each record is close
843
         * to full.  This produces fewer records, but it means that messages can
844
         * be quite fragmented.  Adding an extra flush here would push new
845
         * messages into new records and reduce fragmentation. */
846
84.1k
        if (msg->type == ssl_ct_handshake) {
847
80.5k
            rv = dtls_FragmentHandshake(ss, msg);
848
80.5k
        } else {
849
3.52k
            PORT_Assert(!tls13_MaybeTls13(ss));
850
3.52k
            rv = dtls_SendFragment(ss, msg, msg->data, msg->len);
851
3.52k
        }
852
84.1k
        if (rv != SECSuccess) {
853
0
            break;
854
0
        }
855
84.1k
    }
856
857
    /* Finally, flush any data that wasn't flushed already. */
858
35.4k
    if (rv == SECSuccess) {
859
35.4k
        rv = dtls_SendSavedWriteData(ss);
860
35.4k
    }
861
862
    /* Give up the locks */
863
35.4k
    ssl_ReleaseSpecReadLock(ss);
864
35.4k
    ssl_ReleaseXmitBufLock(ss);
865
866
35.4k
    return rv;
867
35.4k
}
868
869
/* Flush the data in the pendingBuf and update the max message sent
870
 * so we can adjust the MTU estimate if we need to.
871
 * Wrapper for ssl_SendSavedWriteData.
872
 *
873
 * Called from dtls_TransmitMessageFlight()
874
 */
875
static SECStatus
876
dtls_SendSavedWriteData(sslSocket *ss)
877
51.5k
{
878
51.5k
    PRInt32 sent;
879
880
51.5k
    sent = ssl_SendSavedWriteData(ss);
881
51.5k
    if (sent < 0)
882
0
        return SECFailure;
883
884
    /* We should always have complete writes b/c datagram sockets
885
     * don't really block */
886
51.5k
    if (ss->pendingBuf.len > 0) {
887
0
        ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
888
0
        return SECFailure;
889
0
    }
890
891
    /* Update the largest message sent so we can adjust the MTU
892
     * estimate if necessary */
893
51.5k
    if (sent > ss->ssl3.hs.maxMessageSent)
894
26.8k
        ss->ssl3.hs.maxMessageSent = sent;
895
896
51.5k
    return SECSuccess;
897
51.5k
}
898
899
void
900
dtls_InitTimers(sslSocket *ss)
901
66.4k
{
902
66.4k
    unsigned int i;
903
66.4k
    dtlsTimer **timers[PR_ARRAY_SIZE(ss->ssl3.hs.timers)] = {
904
66.4k
        &ss->ssl3.hs.rtTimer,
905
66.4k
        &ss->ssl3.hs.ackTimer,
906
66.4k
        &ss->ssl3.hs.hdTimer
907
66.4k
    };
908
66.4k
    static const char *timerLabels[] = {
909
66.4k
        "retransmit", "ack", "holddown"
910
66.4k
    };
911
912
66.4k
    PORT_Assert(PR_ARRAY_SIZE(timers) == PR_ARRAY_SIZE(timerLabels));
913
265k
    for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
914
199k
        *timers[i] = &ss->ssl3.hs.timers[i];
915
199k
        ss->ssl3.hs.timers[i].label = timerLabels[i];
916
199k
    }
917
66.4k
}
918
919
SECStatus
920
dtls_StartTimer(sslSocket *ss, dtlsTimer *timer, PRUint32 time, DTLSTimerCb cb)
921
34.4k
{
922
34.4k
    PORT_Assert(timer->cb == NULL);
923
924
34.4k
    SSL_TRC(10, ("%d: SSL3[%d]: %s dtls_StartTimer %s timeout=%d",
925
34.4k
                 SSL_GETPID(), ss->fd, SSL_ROLE(ss), timer->label, time));
926
927
34.4k
    timer->started = PR_IntervalNow();
928
34.4k
    timer->timeout = time;
929
34.4k
    timer->cb = cb;
930
34.4k
    return SECSuccess;
931
34.4k
}
932
933
SECStatus
934
dtls_RestartTimer(sslSocket *ss, dtlsTimer *timer)
935
2.36k
{
936
2.36k
    timer->started = PR_IntervalNow();
937
2.36k
    return SECSuccess;
938
2.36k
}
939
940
PRBool
941
dtls_TimerActive(sslSocket *ss, dtlsTimer *timer)
942
32.1k
{
943
32.1k
    return timer->cb != NULL;
944
32.1k
}
945
946
/* Start a timer for retransmission. */
947
static SECStatus
948
dtls_StartRetransmitTimer(sslSocket *ss)
949
32.1k
{
950
32.1k
    dtlsTimer *timer = ss->ssl3.hs.rtTimer;
951
32.1k
    PRUint32 timeout = DTLS_RETRANSMIT_INITIAL_MS;
952
953
32.1k
    if (dtls_TimerActive(ss, timer)) {
954
0
        SSL_TRC(10, ("%d: SSL3[%d]: %s dtls timer %s is already active, restarting. New timeout is %d",
955
0
                     SSL_GETPID(), ss->fd, SSL_ROLE(ss),
956
0
                     timer->label, timeout));
957
        // If a post-handshake message has already been sent (thus activating the
958
        // timer) and a second one is queued, reset the timer so no message waits
959
        // longer than the minimum delay. The first message is retransmitted a
960
        // bit more aggressively than it otherwise would be, but this is
961
        // unlikely to be a problem.
962
0
        (void)dtls_RestartTimer(ss, timer);
963
0
        ss->ssl3.hs.rtRetries = 0;
964
0
        timer->timeout = timeout;
965
0
        return SECSuccess;
966
0
    }
967
968
32.1k
    ss->ssl3.hs.rtRetries = 0;
969
32.1k
    return dtls_StartTimer(ss, timer,
970
32.1k
                           timeout,
971
32.1k
                           dtls_RetransmitTimerExpiredCb);
972
32.1k
}
973
974
/* Start a timer for holding an old cipher spec. */
975
SECStatus
976
dtls_StartHolddownTimer(sslSocket *ss)
977
384
{
978
    /* DTLS1.3 starts the timer without calling this function, see tls13_ServerHandleFinished.*/
979
384
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
980
384
    return dtls_StartTimer(ss, ss->ssl3.hs.hdTimer,
981
384
                           DTLS_RETRANSMIT_FINISHED_MS,
982
384
                           dtls_FinishedTimerCb);
983
384
}
984
985
/* Cancel a pending timer
986
 *
987
 * Called from:
988
 *              dtls_HandleHandshake()
989
 *              dtls_CheckTimer()
990
 */
991
void
992
dtls_CancelTimer(sslSocket *ss, dtlsTimer *timer)
993
73.1k
{
994
73.1k
    SSL_TRC(30, ("%d: SSL3[%d]: %s dtls_CancelTimer %s",
995
73.1k
                 SSL_GETPID(), ss->fd, SSL_ROLE(ss),
996
73.1k
                 timer->label));
997
998
73.1k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
999
1000
73.1k
    timer->cb = NULL;
1001
73.1k
}
1002
1003
static void
1004
dtls_CancelAllTimers(sslSocket *ss)
1005
12.9k
{
1006
12.9k
    unsigned int i;
1007
1008
51.6k
    for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
1009
38.7k
        dtls_CancelTimer(ss, &ss->ssl3.hs.timers[i]);
1010
38.7k
    }
1011
12.9k
}
1012
1013
/* Check the pending timer and fire the callback if it expired
1014
 *
1015
 * Called from ssl3_GatherCompleteHandshake()
1016
 */
1017
void
1018
dtls_CheckTimer(sslSocket *ss)
1019
26.1k
{
1020
26.1k
    unsigned int i;
1021
26.1k
    SSL_TRC(30, ("%d: SSL3[%d]: dtls_CheckTimer (%s)",
1022
26.1k
                 SSL_GETPID(), ss->fd, ss->sec.isServer ? "server" : "client"));
1023
1024
26.1k
    ssl_GetSSL3HandshakeLock(ss);
1025
1026
104k
    for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
1027
78.3k
        dtlsTimer *timer = &ss->ssl3.hs.timers[i];
1028
78.3k
        if (!timer->cb) {
1029
55.7k
            continue;
1030
55.7k
        }
1031
1032
22.6k
        if ((PR_IntervalNow() - timer->started) >=
1033
22.6k
            PR_MillisecondsToInterval(timer->timeout)) {
1034
            /* Timer has expired */
1035
58
            DTLSTimerCb cb = timer->cb;
1036
1037
58
            SSL_TRC(10, ("%d: SSL3[%d]: %s firing timer %s",
1038
58
                         SSL_GETPID(), ss->fd, SSL_ROLE(ss),
1039
58
                         timer->label));
1040
1041
            /* Cancel the timer so that we can call the CB safely */
1042
58
            dtls_CancelTimer(ss, timer);
1043
1044
            /* Now call the CB */
1045
58
            cb(ss);
1046
58
        }
1047
22.6k
    }
1048
26.1k
    ssl_ReleaseSSL3HandshakeLock(ss);
1049
26.1k
}
1050
1051
/* The callback to fire when the holddown timer for the Finished
1052
 * message expires and we can delete it
1053
 *
1054
 * Called from dtls_CheckTimer()
1055
 */
1056
static void
1057
dtls_FinishedTimerCb(sslSocket *ss)
1058
0
{
1059
0
    dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
1060
0
}
1061
1062
/* Cancel the Finished hold-down timer and destroy the
1063
 * pending cipher spec. Note that this means that
1064
 * successive rehandshakes will fail if the Finished is
1065
 * lost.
1066
 *
1067
 * XXX OK for now. Figure out how to handle the combination
1068
 * of Finished lost and rehandshake
1069
 */
1070
void
1071
dtls_RehandshakeCleanup(sslSocket *ss)
1072
13.1k
{
1073
    /* Skip this if we are handling a second ClientHello. */
1074
13.1k
    if (ss->ssl3.hs.helloRetry) {
1075
206
        return;
1076
206
    }
1077
12.9k
    PORT_Assert((ss->version < SSL_LIBRARY_VERSION_TLS_1_3));
1078
12.9k
    dtls_CancelAllTimers(ss);
1079
12.9k
    dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
1080
12.9k
    ss->ssl3.hs.sendMessageSeq = 0;
1081
12.9k
    ss->ssl3.hs.recvMessageSeq = 0;
1082
12.9k
}
1083
1084
/* Set the MTU to the next step less than or equal to the
1085
 * advertised value. Also used to downgrade the MTU by
1086
 * doing dtls_SetMTU(ss, biggest packet set).
1087
 *
1088
 * Passing 0 means set this to the largest MTU known
1089
 * (effectively resetting the PMTU backoff value).
1090
 *
1091
 * Called by:
1092
 *            ssl3_InitState()
1093
 *            dtls_RetransmitTimerExpiredCb()
1094
 */
1095
void
1096
dtls_SetMTU(sslSocket *ss, PRUint16 advertised)
1097
30.6k
{
1098
30.6k
    int i;
1099
1100
30.6k
    if (advertised == 0) {
1101
30.6k
        ss->ssl3.mtu = COMMON_MTU_VALUES[0];
1102
30.6k
        SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu));
1103
30.6k
        return;
1104
30.6k
    }
1105
1106
0
    for (i = 0; i < PR_ARRAY_SIZE(COMMON_MTU_VALUES); i++) {
1107
0
        if (COMMON_MTU_VALUES[i] <= advertised) {
1108
0
            ss->ssl3.mtu = COMMON_MTU_VALUES[i];
1109
0
            SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu));
1110
0
            return;
1111
0
        }
1112
0
    }
1113
1114
    /* Fallback */
1115
0
    ss->ssl3.mtu = COMMON_MTU_VALUES[PR_ARRAY_SIZE(COMMON_MTU_VALUES) - 1];
1116
0
    SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu));
1117
0
}
1118
1119
/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a
1120
 * DTLS hello_verify_request
1121
 * Caller must hold Handshake and RecvBuf locks.
1122
 */
1123
SECStatus
1124
dtls_HandleHelloVerifyRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
1125
699
{
1126
699
    int errCode = SSL_ERROR_RX_MALFORMED_HELLO_VERIFY_REQUEST;
1127
699
    SECStatus rv;
1128
699
    SSL3ProtocolVersion temp;
1129
699
    SSL3AlertDescription desc = illegal_parameter;
1130
1131
699
    SSL_TRC(3, ("%d: SSL3[%d]: handle hello_verify_request handshake",
1132
699
                SSL_GETPID(), ss->fd));
1133
699
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
1134
699
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1135
1136
699
    if (ss->ssl3.hs.ws != wait_server_hello) {
1137
4
        errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST;
1138
4
        desc = unexpected_message;
1139
4
        goto alert_loser;
1140
4
    }
1141
1142
695
    dtls_ReceivedFirstMessageInFlight(ss);
1143
1144
    /* The version.
1145
     *
1146
     * RFC 4347 required that you verify that the server versions
1147
     * match (Section 4.2.1) in the HelloVerifyRequest and the
1148
     * ServerHello.
1149
     *
1150
     * RFC 6347 (Section 4.2.1) suggests (SHOULD) that servers always use 1.0 in
1151
     * HelloVerifyRequest and allows the versions not to match,
1152
     * especially when 1.2 is being negotiated.
1153
     *
1154
     * Therefore we do not do anything to enforce a match, just
1155
     * read and check that this value is sane.
1156
     */
1157
695
    rv = ssl_ClientReadVersion(ss, &b, &length, &temp);
1158
695
    if (rv != SECSuccess) {
1159
54
        goto loser; /* alert has been sent */
1160
54
    }
1161
1162
    /* Read the cookie.
1163
     * IMPORTANT: The value of ss->ssl3.hs.cookie is only valid while the
1164
     * HelloVerifyRequest message remains valid. */
1165
641
    rv = ssl3_ConsumeHandshakeVariable(ss, &ss->ssl3.hs.cookie, 1, &b, &length);
1166
641
    if (rv != SECSuccess) {
1167
23
        goto loser; /* alert has been sent */
1168
23
    }
1169
618
    if (ss->ssl3.hs.cookie.len > DTLS_COOKIE_BYTES) {
1170
2
        desc = decode_error;
1171
2
        goto alert_loser; /* malformed. */
1172
2
    }
1173
1174
616
    ssl_GetXmitBufLock(ss); /*******************************/
1175
1176
    /* Now re-send the client hello */
1177
616
    rv = ssl3_SendClientHello(ss, client_hello_retransmit);
1178
1179
616
    ssl_ReleaseXmitBufLock(ss); /*******************************/
1180
1181
616
    if (rv == SECSuccess)
1182
616
        return rv;
1183
1184
6
alert_loser:
1185
6
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
1186
1187
83
loser:
1188
83
    ssl_MapLowLevelError(errCode);
1189
83
    return SECFailure;
1190
6
}
1191
1192
/* Initialize the DTLS anti-replay window
1193
 *
1194
 * Called from:
1195
 *              ssl3_SetupPendingCipherSpec()
1196
 *              ssl3_InitCipherSpec()
1197
 */
1198
void
1199
dtls_InitRecvdRecords(DTLSRecvdRecords *records)
1200
157k
{
1201
157k
    PORT_Memset(records->data, 0, sizeof(records->data));
1202
157k
    records->left = 0;
1203
157k
    records->right = DTLS_RECVD_RECORDS_WINDOW - 1;
1204
157k
}
1205
1206
/*
1207
 * Has this DTLS record been received? Return values are:
1208
 * -1 -- out of range to the left
1209
 *  0 -- not received yet
1210
 *  1 -- replay
1211
 *
1212
 *  Called from: ssl3_HandleRecord()
1213
 */
1214
int
1215
dtls_RecordGetRecvd(const DTLSRecvdRecords *records, sslSequenceNumber seq)
1216
3.51M
{
1217
3.51M
    PRUint64 offset;
1218
1219
    /* Out of range to the left */
1220
3.51M
    if (seq < records->left) {
1221
3.13M
        return -1;
1222
3.13M
    }
1223
1224
    /* Out of range to the right; since we advance the window on
1225
     * receipt, that means that this packet has not been received
1226
     * yet */
1227
375k
    if (seq > records->right)
1228
121k
        return 0;
1229
1230
253k
    offset = seq % DTLS_RECVD_RECORDS_WINDOW;
1231
1232
253k
    return !!(records->data[offset / 8] & (1 << (offset % 8)));
1233
375k
}
1234
1235
/* Update the DTLS anti-replay window
1236
 *
1237
 * Called from ssl3_HandleRecord()
1238
 */
1239
void
1240
dtls_RecordSetRecvd(DTLSRecvdRecords *records, sslSequenceNumber seq)
1241
91.4k
{
1242
91.4k
    PRUint64 offset;
1243
1244
91.4k
    if (seq < records->left)
1245
0
        return;
1246
1247
91.4k
    if (seq > records->right) {
1248
26.7k
        sslSequenceNumber new_left;
1249
26.7k
        sslSequenceNumber new_right;
1250
26.7k
        sslSequenceNumber right;
1251
1252
        /* Slide to the right; this is the tricky part
1253
         *
1254
         * 1. new_top is set to have room for seq, on the
1255
         *    next byte boundary by setting the right 8
1256
         *    bits of seq
1257
         * 2. new_left is set to compensate.
1258
         * 3. Zero all bits between top and new_top. Since
1259
         *    this is a ring, this zeroes everything as-yet
1260
         *    unseen. Because we always operate on byte
1261
         *    boundaries, we can zero one byte at a time
1262
         */
1263
26.7k
        new_right = seq | 0x07;
1264
26.7k
        new_left = (new_right - DTLS_RECVD_RECORDS_WINDOW) + 1;
1265
1266
26.7k
        if (new_right > records->right + DTLS_RECVD_RECORDS_WINDOW) {
1267
24.4k
            PORT_Memset(records->data, 0, sizeof(records->data));
1268
24.4k
        } else {
1269
72.5k
            for (right = records->right + 8; right <= new_right; right += 8) {
1270
70.2k
                offset = right % DTLS_RECVD_RECORDS_WINDOW;
1271
70.2k
                records->data[offset / 8] = 0;
1272
70.2k
            }
1273
2.28k
        }
1274
1275
26.7k
        records->right = new_right;
1276
26.7k
        records->left = new_left;
1277
26.7k
    }
1278
1279
91.4k
    offset = seq % DTLS_RECVD_RECORDS_WINDOW;
1280
1281
91.4k
    records->data[offset / 8] |= (1 << (offset % 8));
1282
91.4k
}
1283
1284
SECStatus
1285
DTLS_GetHandshakeTimeout(PRFileDesc *socket, PRIntervalTime *timeout)
1286
0
{
1287
0
    sslSocket *ss = NULL;
1288
0
    PRBool found = PR_FALSE;
1289
0
    PRIntervalTime now = PR_IntervalNow();
1290
0
    PRIntervalTime to;
1291
0
    unsigned int i;
1292
1293
0
    *timeout = PR_INTERVAL_NO_TIMEOUT;
1294
1295
0
    ss = ssl_FindSocket(socket);
1296
1297
0
    if (!ss) {
1298
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1299
0
        return SECFailure;
1300
0
    }
1301
1302
0
    if (!IS_DTLS(ss)) {
1303
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1304
0
        return SECFailure;
1305
0
    }
1306
1307
0
    for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
1308
0
        PRIntervalTime elapsed;
1309
0
        PRIntervalTime desired;
1310
0
        dtlsTimer *timer = &ss->ssl3.hs.timers[i];
1311
1312
0
        if (!timer->cb) {
1313
0
            continue;
1314
0
        }
1315
0
        found = PR_TRUE;
1316
1317
0
        elapsed = now - timer->started;
1318
0
        desired = PR_MillisecondsToInterval(timer->timeout);
1319
0
        if (elapsed > desired) {
1320
            /* Timer expired */
1321
0
            *timeout = PR_INTERVAL_NO_WAIT;
1322
0
            return SECSuccess;
1323
0
        } else {
1324
0
            to = desired - elapsed;
1325
0
        }
1326
1327
0
        if (*timeout > to) {
1328
0
            *timeout = to;
1329
0
        }
1330
0
    }
1331
1332
0
    if (!found) {
1333
0
        PORT_SetError(SSL_ERROR_NO_TIMERS_FOUND);
1334
0
        return SECFailure;
1335
0
    }
1336
1337
0
    return SECSuccess;
1338
0
}
1339
1340
PRBool
1341
dtls_IsLongHeader(SSL3ProtocolVersion version, PRUint8 firstOctet)
1342
13.6M
{
1343
#ifndef UNSAFE_FUZZER_MODE
1344
9.08M
    return version < SSL_LIBRARY_VERSION_TLS_1_3 ||
1345
107k
           firstOctet == ssl_ct_handshake ||
1346
99.6k
           firstOctet == ssl_ct_ack ||
1347
94.8k
           firstOctet == ssl_ct_alert;
1348
#else
1349
4.53M
    return PR_TRUE;
1350
#endif
1351
13.6M
}
dtls_IsLongHeader
Line
Count
Source
1342
4.53M
{
1343
#ifndef UNSAFE_FUZZER_MODE
1344
    return version < SSL_LIBRARY_VERSION_TLS_1_3 ||
1345
           firstOctet == ssl_ct_handshake ||
1346
           firstOctet == ssl_ct_ack ||
1347
           firstOctet == ssl_ct_alert;
1348
#else
1349
4.53M
    return PR_TRUE;
1350
4.53M
#endif
1351
4.53M
}
dtls_IsLongHeader
Line
Count
Source
1342
9.08M
{
1343
9.08M
#ifndef UNSAFE_FUZZER_MODE
1344
9.08M
    return version < SSL_LIBRARY_VERSION_TLS_1_3 ||
1345
107k
           firstOctet == ssl_ct_handshake ||
1346
99.6k
           firstOctet == ssl_ct_ack ||
1347
94.8k
           firstOctet == ssl_ct_alert;
1348
#else
1349
    return PR_TRUE;
1350
#endif
1351
9.08M
}
1352
1353
PRBool
1354
dtls_IsDtls13Ciphertext(SSL3ProtocolVersion version, PRUint8 firstOctet)
1355
178k
{
1356
    // Allow no version in case we haven't negotiated one yet.
1357
178k
    return (version == 0 || version >= SSL_LIBRARY_VERSION_TLS_1_3) &&
1358
178k
           (firstOctet & 0xe0) == 0x20;
1359
178k
}
1360
1361
DTLSEpoch
1362
dtls_ReadEpoch(const SSL3ProtocolVersion version, const DTLSEpoch specEpoch, const PRUint8 *hdr)
1363
5.04M
{
1364
5.04M
    if (dtls_IsLongHeader(version, hdr[0])) {
1365
5.03M
        return ((DTLSEpoch)hdr[3] << 8) | hdr[4];
1366
5.03M
    }
1367
1368
13.0k
    DTLSEpoch epoch = (specEpoch & ~3) | (hdr[0] & 3);
1369
    /* The epoch cannot be higher than the current read epoch,
1370
        though guard against underflow. */
1371
13.0k
    if (epoch > specEpoch && epoch > 4) {
1372
0
        epoch -= 4;
1373
0
    }
1374
1375
13.0k
    return epoch;
1376
5.04M
}
1377
1378
static sslSequenceNumber
1379
dtls_ReadSequenceNumber(const ssl3CipherSpec *spec, const PRUint8 *hdr)
1380
3.51M
{
1381
3.51M
    sslSequenceNumber cap;
1382
3.51M
    sslSequenceNumber partial;
1383
3.51M
    sslSequenceNumber seqNum;
1384
3.51M
    sslSequenceNumber mask;
1385
1386
3.51M
    if (dtls_IsLongHeader(spec->version, hdr[0])) {
1387
3.50M
        static const unsigned int seqNumOffset = 5; /* type, version, epoch */
1388
3.50M
        static const unsigned int seqNumLength = 6;
1389
3.50M
        sslReader r = SSL_READER(hdr + seqNumOffset, seqNumLength);
1390
3.50M
        (void)sslRead_ReadNumber(&r, seqNumLength, &seqNum);
1391
3.50M
        return seqNum;
1392
3.50M
    }
1393
1394
    /* Only the least significant bits of the sequence number is available here.
1395
     * This recovers the value based on the next expected sequence number.
1396
     *
1397
     * This works by determining the maximum possible sequence number, which is
1398
     * half the range of possible values above the expected next value (the
1399
     * expected next value is in |spec->seqNum|).  Then, the last part of the
1400
     * sequence number is replaced.  If that causes the value to exceed the
1401
     * maximum, subtract an entire range.
1402
     */
1403
10.1k
    if (hdr[0] & 0x08) {
1404
9.45k
        cap = spec->nextSeqNum + (1ULL << 15);
1405
9.45k
        partial = (((sslSequenceNumber)hdr[1]) << 8) |
1406
9.45k
                  (sslSequenceNumber)hdr[2];
1407
9.45k
        mask = (1ULL << 16) - 1;
1408
9.45k
    } else {
1409
709
        cap = spec->nextSeqNum + (1ULL << 7);
1410
709
        partial = (sslSequenceNumber)hdr[1];
1411
709
        mask = (1ULL << 8) - 1;
1412
709
    }
1413
10.1k
    seqNum = (cap & ~mask) | partial;
1414
    /* The second check prevents the value from underflowing if we get a large
1415
     * gap at the start of a connection, where this subtraction would cause the
1416
     * sequence number to wrap to near UINT64_MAX. */
1417
10.1k
    if ((partial > (cap & mask)) && (seqNum > mask)) {
1418
0
        seqNum -= mask + 1;
1419
0
    }
1420
10.1k
    return seqNum;
1421
3.51M
}
1422
1423
/*
1424
 * DTLS relevance checks:
1425
 * Note that this code currently ignores all out-of-epoch packets,
1426
 * which means we lose some in the case of rehandshake +
1427
 * loss/reordering. Since DTLS is explicitly unreliable, this
1428
 * seems like a good tradeoff for implementation effort and is
1429
 * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1.
1430
 *
1431
 * If the packet is not relevant, this function returns PR_FALSE.  If the packet
1432
 * is relevant, this function returns PR_TRUE and sets |*seqNumOut| to the
1433
 * packet sequence number (removing the epoch).
1434
 */
1435
PRBool
1436
dtls_IsRelevant(sslSocket *ss, const ssl3CipherSpec *spec,
1437
                const SSL3Ciphertext *cText,
1438
                sslSequenceNumber *seqNumOut)
1439
3.51M
{
1440
3.51M
    sslSequenceNumber seqNum = dtls_ReadSequenceNumber(spec, cText->hdr);
1441
3.51M
    if (dtls_RecordGetRecvd(&spec->recvdRecords, seqNum) != 0) {
1442
3.29M
        SSL_TRC(10, ("%d: SSL3[%d]: dtls_IsRelevant, rejecting "
1443
3.29M
                     "potentially replayed packet",
1444
3.29M
                     SSL_GETPID(), ss->fd));
1445
3.29M
        return PR_FALSE;
1446
3.29M
    }
1447
1448
216k
    *seqNumOut = seqNum;
1449
216k
    return PR_TRUE;
1450
3.51M
}
1451
1452
void
1453
dtls_ReceivedFirstMessageInFlight(sslSocket *ss)
1454
192k
{
1455
192k
    if (!IS_DTLS(ss))
1456
161k
        return;
1457
1458
    /* At this point we are advancing our state machine, so we can free our last
1459
     * flight of messages. */
1460
31.6k
    if (ss->ssl3.hs.ws != idle_handshake ||
1461
31.6k
        ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
1462
        /* We need to keep our last flight around in DTLS 1.2 and below,
1463
         * so we can retransmit it in response to other people's
1464
         * retransmits. */
1465
31.6k
        dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
1466
1467
        /* Reset the timer to the initial value if the retry counter
1468
         * is 0, per RFC 6347, Sec. 4.2.4.1 */
1469
31.6k
        dtls_CancelTimer(ss, ss->ssl3.hs.rtTimer);
1470
31.6k
        if (ss->ssl3.hs.rtRetries == 0) {
1471
31.6k
            ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS;
1472
31.6k
        }
1473
31.6k
    }
1474
1475
    /* Empty the ACK queue (TLS 1.3 only). */
1476
    ssl_ClearPRCList(&ss->ssl3.hs.dtlsRcvdHandshake, NULL);
1477
31.6k
}