tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

dtlscon.c (47810B)


      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 #define DTLS_COOKIE_BYTES 32
     34 /* Maximum DTLS expansion = header + IV + max CBC padding +
     35 * maximum MAC. */
     36 #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 {
     61    if (tlsv == SSL_LIBRARY_VERSION_TLS_1_1) {
     62        return SSL_LIBRARY_VERSION_DTLS_1_0_WIRE;
     63    }
     64    if (tlsv == SSL_LIBRARY_VERSION_TLS_1_2) {
     65        return SSL_LIBRARY_VERSION_DTLS_1_2_WIRE;
     66    }
     67    if (tlsv == SSL_LIBRARY_VERSION_TLS_1_3) {
     68        return SSL_LIBRARY_VERSION_DTLS_1_3_WIRE;
     69    }
     70 
     71    /* Anything else is an error, so return
     72     * the invalid version 0xffff. */
     73    return 0xffff;
     74 }
     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 {
     83    if (MSB(dtlsv) == 0xff) {
     84        return 0;
     85    }
     86 
     87    if (dtlsv == SSL_LIBRARY_VERSION_DTLS_1_0_WIRE) {
     88        return SSL_LIBRARY_VERSION_TLS_1_1;
     89    }
     90    /* Handle the skipped version of DTLS 1.1 by returning
     91     * an error. */
     92    if (dtlsv == ((~0x0101) & 0xffff)) {
     93        return 0;
     94    }
     95    if (dtlsv == SSL_LIBRARY_VERSION_DTLS_1_2_WIRE) {
     96        return SSL_LIBRARY_VERSION_TLS_1_2;
     97    }
     98    if (dtlsv == SSL_LIBRARY_VERSION_DTLS_1_3_WIRE) {
     99        return SSL_LIBRARY_VERSION_TLS_1_3;
    100    }
    101 
    102    /* Return a fictional higher version than we know of */
    103    return SSL_LIBRARY_VERSION_MAX_SUPPORTED + 1;
    104 }
    105 
    106 /* On this socket, Disable non-DTLS cipher suites in the argument's list */
    107 SECStatus
    108 ssl3_DisableNonDTLSSuites(sslSocket *ss)
    109 {
    110    const ssl3CipherSuite *suite;
    111 
    112    for (suite = nonDTLSSuites; *suite; ++suite) {
    113        PORT_CheckSuccess(ssl3_CipherPrefSet(ss, *suite, PR_FALSE));
    114    }
    115    return SECSuccess;
    116 }
    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 {
    126    DTLSQueuedMessage *msg;
    127 
    128    msg = PORT_ZNew(DTLSQueuedMessage);
    129    if (!msg)
    130        return NULL;
    131 
    132    msg->data = PORT_Alloc(len);
    133    if (!msg->data) {
    134        PORT_Free(msg);
    135        return NULL;
    136    }
    137    PORT_Memcpy(msg->data, data, len);
    138 
    139    msg->len = len;
    140    msg->cwSpec = cwSpec;
    141    msg->type = ct;
    142    /* Safe if we are < 1.3, since the refct is
    143     * already very high. */
    144    ssl_CipherSpecAddRef(cwSpec);
    145 
    146    return msg;
    147 }
    148 
    149 /*
    150 * Free a handshake message
    151 *
    152 * Called from dtls_FreeHandshakeMessages()
    153 */
    154 void
    155 dtls_FreeHandshakeMessage(DTLSQueuedMessage *msg)
    156 {
    157    if (!msg)
    158        return;
    159 
    160    /* Safe if we are < 1.3, since the refct is
    161     * already very high. */
    162    ssl_CipherSpecRelease(msg->cwSpec);
    163    PORT_ZFree(msg->data, msg->len);
    164    PORT_Free(msg);
    165 }
    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 {
    177    PRCList *cur_p;
    178 
    179    while (!PR_CLIST_IS_EMPTY(list)) {
    180        cur_p = PR_LIST_TAIL(list);
    181        PR_REMOVE_LINK(cur_p);
    182        dtls_FreeHandshakeMessage((DTLSQueuedMessage *)cur_p);
    183    }
    184 }
    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 {
    191    dtlsTimer *rtTimer = ss->ssl3.hs.rtTimer;
    192    dtlsTimer *hdTimer = ss->ssl3.hs.hdTimer;
    193    SECStatus rv = SECSuccess;
    194 
    195    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
    196    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
    197 
    198    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        if ((PR_IntervalNow() - rtTimer->started) >
    205            (rtTimer->timeout / 4)) {
    206            SSL_TRC(30,
    207                    ("%d: SSL3[%d]: Shortcutting retransmit timer",
    208                     SSL_GETPID(), ss->fd));
    209 
    210            /* Cancel the timer and call the CB,
    211             * which re-arms the timer */
    212            dtls_CancelTimer(ss, ss->ssl3.hs.rtTimer);
    213            dtls_RetransmitTimerExpiredCb(ss);
    214        } else {
    215            SSL_TRC(30,
    216                    ("%d: SSL3[%d]: Ignoring retransmission: "
    217                     "last retransmission %dms ago, suppressed for %dms",
    218                     SSL_GETPID(), ss->fd,
    219                     PR_IntervalNow() - rtTimer->started,
    220                     rtTimer->timeout / 4));
    221        }
    222    } else if (hdTimer->cb == dtls_FinishedTimerCb) {
    223        SSL_TRC(30, ("%d: SSL3[%d]: Retransmit detected in holddown",
    224                     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        dtls_CancelTimer(ss, ss->ssl3.hs.hdTimer);
    231        rv = dtls_TransmitMessageFlight(ss);
    232        if (rv == SECSuccess) {
    233            rv = dtls_StartHolddownTimer(ss);
    234        }
    235    } else {
    236        /* Otherwise handled in dtls13_HandleOutOfEpochRecord. */
    237        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
    238            PORT_Assert(hdTimer->cb == NULL);
    239        }
    240 
    241        PORT_Assert(rtTimer->cb == NULL);
    242        /* ... and ignore it. */
    243    }
    244    return rv;
    245 }
    246 
    247 static SECStatus
    248 dtls_HandleHandshakeMessage(sslSocket *ss, PRUint8 *data, PRBool last)
    249 {
    250    ss->ssl3.hs.recvdHighWater = -1;
    251 
    252    return ssl3_HandleHandshakeMessage(ss, data, ss->ssl3.hs.msg_len,
    253                                       last);
    254 }
    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 #define OFFSET_BYTE(o) (o / 8)
    271 #define OFFSET_MASK(o) (1 << (o % 8))
    272 
    273 SECStatus
    274 dtls_HandleHandshake(sslSocket *ss, DTLSEpoch epoch, sslSequenceNumber seqNum,
    275                     sslBuffer *origBuf)
    276 {
    277    sslBuffer buf = *origBuf;
    278    SECStatus rv = SECSuccess;
    279    PRBool discarded = PR_FALSE;
    280 
    281    ss->ssl3.hs.endOfFlight = PR_FALSE;
    282 
    283    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
    284    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
    285 
    286    while (buf.len > 0) {
    287        PRUint8 type;
    288        PRUint32 message_length;
    289        PRUint16 message_seq;
    290        PRUint32 fragment_offset;
    291        PRUint32 fragment_length;
    292        PRUint32 offset;
    293 
    294        if (buf.len < 12) {
    295            PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
    296            rv = SECFailure;
    297            goto loser;
    298        }
    299 
    300        /* Parse the header */
    301        type = buf.buf[0];
    302        message_length = (buf.buf[1] << 16) | (buf.buf[2] << 8) | buf.buf[3];
    303        message_seq = (buf.buf[4] << 8) | buf.buf[5];
    304        fragment_offset = (buf.buf[6] << 16) | (buf.buf[7] << 8) | buf.buf[8];
    305        fragment_length = (buf.buf[9] << 16) | (buf.buf[10] << 8) | buf.buf[11];
    306 
    307 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
    308        if (message_length > MAX_HANDSHAKE_MSG_LEN) {
    309            (void)ssl3_DecodeError(ss);
    310            PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
    311            rv = SECFailure;
    312            goto loser;
    313        }
    314 #undef MAX_HANDSHAKE_MSG_LEN
    315 
    316        buf.buf += 12;
    317        buf.len -= 12;
    318 
    319        /* This fragment must be complete */
    320        if (buf.len < fragment_length) {
    321            PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
    322            rv = SECFailure;
    323            goto loser;
    324        }
    325 
    326        /* Sanity check the packet contents */
    327        if ((fragment_length + fragment_offset) > message_length) {
    328            PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
    329            rv = SECFailure;
    330            goto loser;
    331        }
    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        if (message_seq > ss->ssl3.hs.recvMessageSeq &&
    338            message_seq == 1 &&
    339            fragment_offset == 0 &&
    340            ss->ssl3.hs.ws == wait_client_hello &&
    341            (SSLHandshakeType)type == ssl_hs_client_hello) {
    342            SSL_TRC(5, ("%d: DTLS[%d]: Received apparent 2nd ClientHello",
    343                        SSL_GETPID(), ss->fd));
    344            ss->ssl3.hs.recvMessageSeq = 1;
    345            ss->ssl3.hs.helloRetry = PR_TRUE;
    346        }
    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        if ((message_seq == ss->ssl3.hs.recvMessageSeq) &&
    358            (fragment_offset == 0) &&
    359            (fragment_length == message_length)) {
    360            /* Complete next message. Process immediately */
    361            ss->ssl3.hs.msg_type = (SSLHandshakeType)type;
    362            ss->ssl3.hs.msg_len = message_length;
    363 
    364            rv = dtls_HandleHandshakeMessage(ss, buf.buf,
    365                                             buf.len == fragment_length);
    366            if (rv != SECSuccess) {
    367                goto loser;
    368            }
    369        } else {
    370            if (message_seq < ss->ssl3.hs.recvMessageSeq) {
    371                /* Case 3: we do an immediate retransmit if we're
    372                 * in a waiting state. */
    373                rv = dtls_RetransmitDetected(ss);
    374                goto loser;
    375            } 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                SSL_TRC(10, ("%d: SSL3[%d]: dtls_HandleHandshake, discarding handshake message",
    385                             SSL_GETPID(), ss->fd));
    386                discarded = PR_TRUE;
    387            } else {
    388                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                if (ss->ssl3.hs.recvdHighWater == -1) {
    396                    PRUint32 map_length = OFFSET_BYTE(message_length) + 1;
    397 
    398                    rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, message_length);
    399                    if (rv != SECSuccess)
    400                        goto loser;
    401                    /* Make room for the fragment map */
    402                    rv = sslBuffer_Grow(&ss->ssl3.hs.recvdFragments,
    403                                        map_length);
    404                    if (rv != SECSuccess)
    405                        goto loser;
    406 
    407                    /* Reset the reassembly map */
    408                    ss->ssl3.hs.recvdHighWater = 0;
    409                    PORT_Memset(ss->ssl3.hs.recvdFragments.buf, 0,
    410                                ss->ssl3.hs.recvdFragments.space);
    411                    ss->ssl3.hs.msg_type = (SSLHandshakeType)type;
    412                    ss->ssl3.hs.msg_len = message_length;
    413                }
    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                if (message_length != ss->ssl3.hs.msg_len) {
    420                    ss->ssl3.hs.recvdHighWater = -1;
    421                    PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
    422                    rv = SECFailure;
    423                    goto loser;
    424                }
    425 
    426                /* Now copy this fragment into the buffer. */
    427                if (end > ss->ssl3.hs.recvdHighWater) {
    428                    PORT_Memcpy(ss->ssl3.hs.msg_body.buf + fragment_offset,
    429                                buf.buf, fragment_length);
    430                }
    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                if (fragment_offset <= (unsigned int)ss->ssl3.hs.recvdHighWater) {
    444                    /* Either this is the adjacent fragment or an overlapping
    445                     * fragment */
    446                    if (end > ss->ssl3.hs.recvdHighWater) {
    447                        ss->ssl3.hs.recvdHighWater = end;
    448                    }
    449                } else {
    450                    for (offset = fragment_offset; offset < end; offset++) {
    451                        ss->ssl3.hs.recvdFragments.buf[OFFSET_BYTE(offset)] |=
    452                            OFFSET_MASK(offset);
    453                    }
    454                }
    455 
    456                /* Now figure out the new high water mark if appropriate */
    457                for (offset = ss->ssl3.hs.recvdHighWater;
    458                     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                    if (ss->ssl3.hs.recvdFragments.buf[OFFSET_BYTE(offset)] &
    463                        OFFSET_MASK(offset)) {
    464                        ss->ssl3.hs.recvdHighWater++;
    465                    } else {
    466                        break;
    467                    }
    468                }
    469 
    470                /* If we have all the bytes, then we are good to go */
    471                if (ss->ssl3.hs.recvdHighWater == ss->ssl3.hs.msg_len) {
    472                    rv = dtls_HandleHandshakeMessage(ss, ss->ssl3.hs.msg_body.buf,
    473                                                     buf.len == fragment_length);
    474 
    475                    if (rv != SECSuccess) {
    476                        goto loser;
    477                    }
    478                }
    479            }
    480        }
    481 
    482        buf.buf += fragment_length;
    483        buf.len -= fragment_length;
    484    }
    485 
    486    // This should never happen, but belt and suspenders.
    487    if (rv != SECSuccess) {
    488        PORT_Assert(0);
    489        goto loser;
    490    }
    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    if (!discarded && tls13_MaybeTls13(ss)) {
    496        rv = dtls13_RememberFragment(ss, &ss->ssl3.hs.dtlsRcvdHandshake,
    497                                     0, 0, 0, epoch, seqNum);
    498    }
    499    if (rv != SECSuccess) {
    500        goto loser;
    501    }
    502    rv = dtls13_SetupAcks(ss);
    503 
    504 loser:
    505    origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
    506    return rv;
    507 }
    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 {
    519    SECStatus rv = SECSuccess;
    520    DTLSQueuedMessage *msg = NULL;
    521    ssl3CipherSpec *spec;
    522 
    523    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
    524    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
    525 
    526    spec = ss->ssl3.cwSpec;
    527    msg = dtls_AllocQueuedMessage(spec, ct, pIn, nIn);
    528 
    529    if (!msg) {
    530        PORT_SetError(SEC_ERROR_NO_MEMORY);
    531        rv = SECFailure;
    532    } else {
    533        PR_APPEND_LINK(&msg->link, &ss->ssl3.hs.lastMessageFlight);
    534    }
    535 
    536    return rv;
    537 }
    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 {
    550    SECStatus rv = SECSuccess;
    551 
    552    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
    553    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    if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
    558        return rv;
    559 
    560    rv = dtls_QueueMessage(ss, ssl_ct_handshake,
    561                           ss->sec.ci.sendBuf.buf, ss->sec.ci.sendBuf.len);
    562 
    563    /* Whether we succeeded or failed, toss the old handshake data. */
    564    ss->sec.ci.sendBuf.len = 0;
    565    return rv;
    566 }
    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 {
    577    SECStatus rv = SECSuccess;
    578 
    579    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
    580    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
    581 
    582    rv = dtls_StageHandshakeMessage(ss);
    583    if (rv != SECSuccess) {
    584        return rv;
    585    }
    586 
    587    if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
    588        rv = dtls_TransmitMessageFlight(ss);
    589        if (rv != SECSuccess) {
    590            return rv;
    591        }
    592 
    593        if (!(flags & ssl_SEND_FLAG_NO_RETRANSMIT)) {
    594            rv = dtls_StartRetransmitTimer(ss);
    595        } else {
    596            PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
    597        }
    598    }
    599 
    600    return rv;
    601 }
    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 {
    612    SECStatus rv;
    613    dtlsTimer *timer = ss->ssl3.hs.rtTimer;
    614    ss->ssl3.hs.rtRetries++;
    615 
    616    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        dtls_SetMTU(ss, ss->ssl3.hs.maxMessageSent - 1);
    621    }
    622 
    623    rv = dtls_TransmitMessageFlight(ss);
    624    if (rv == SECSuccess) {
    625        /* Re-arm the timer */
    626        timer->timeout *= 2;
    627        if (timer->timeout > DTLS_RETRANSMIT_MAX_MS) {
    628            timer->timeout = DTLS_RETRANSMIT_MAX_MS;
    629        }
    630 
    631        timer->started = PR_IntervalNow();
    632        timer->cb = dtls_RetransmitTimerExpiredCb;
    633 
    634        SSL_TRC(30,
    635                ("%d: SSL3[%d]: Retransmit #%d, next in %d",
    636                 SSL_GETPID(), ss->fd,
    637                 ss->ssl3.hs.rtRetries, timer->timeout));
    638    }
    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 }
    642 
    643 #define DTLS_HS_HDR_LEN 12
    644 #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 {
    652    PRInt32 sent;
    653    SECStatus rv;
    654 
    655    PRINT_BUF(40, (ss, "dtls_SendFragment", data, len));
    656    sent = ssl3_SendRecord(ss, msg->cwSpec, msg->type, data, len,
    657                           ssl_SEND_FLAG_FORCE_INTO_BUFFER);
    658    if (sent != len) {
    659        if (sent != -1) {
    660            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    661        }
    662        return SECFailure;
    663    }
    664 
    665    /* If another fragment won't fit, flush. */
    666    if (ss->ssl3.mtu < ss->pendingBuf.len + DTLS_MIN_FRAGMENT) {
    667        SSL_TRC(20, ("%d: DTLS[%d]: dtls_SendFragment: flush",
    668                     SSL_GETPID(), ss->fd));
    669        rv = dtls_SendSavedWriteData(ss);
    670        if (rv != SECSuccess) {
    671            return SECFailure;
    672        }
    673    }
    674    return SECSuccess;
    675 }
    676 
    677 /* Fragment a handshake message into multiple records and send them. */
    678 static SECStatus
    679 dtls_FragmentHandshake(sslSocket *ss, DTLSQueuedMessage *msg)
    680 {
    681    PRBool fragmentWritten = PR_FALSE;
    682    PRUint16 msgSeq;
    683    PRUint8 *fragment;
    684    PRUint32 fragmentOffset = 0;
    685    PRUint32 fragmentLen;
    686    const PRUint8 *content = msg->data + DTLS_HS_HDR_LEN;
    687    PRUint32 contentLen = msg->len - DTLS_HS_HDR_LEN;
    688    SECStatus rv;
    689 
    690    /* The headers consume 12 bytes so the smallest possible message (i.e., an
    691     * empty one) is 12 bytes. */
    692    PORT_Assert(msg->len >= DTLS_HS_HDR_LEN);
    693 
    694    /* DTLS only supports fragmenting handshaking messages. */
    695    PORT_Assert(msg->type == ssl_ct_handshake);
    696 
    697    msgSeq = (msg->data[4] << 8) | msg->data[5];
    698 
    699    /* do {} while() so that empty messages are sent at least once. */
    700    do {
    701        PRUint8 buf[DTLS_MAX_MTU]; /* >= than largest plausible MTU */
    702        PRBool hasUnackedRange;
    703        PRUint32 end;
    704 
    705        hasUnackedRange = dtls_NextUnackedRange(ss, msgSeq,
    706                                                fragmentOffset, contentLen,
    707                                                &fragmentOffset, &end);
    708        if (!hasUnackedRange) {
    709            SSL_TRC(20, ("%d: SSL3[%d]: FragmentHandshake %d: all acknowledged",
    710                         SSL_GETPID(), ss->fd, msgSeq));
    711            break;
    712        }
    713 
    714        SSL_TRC(20, ("%d: SSL3[%d]: FragmentHandshake %d: unacked=%u-%u",
    715                     SSL_GETPID(), ss->fd, msgSeq, fragmentOffset, end));
    716 
    717        /* Cut down to the data we have available. */
    718        PORT_Assert(fragmentOffset <= contentLen);
    719        PORT_Assert(fragmentOffset <= end);
    720        PORT_Assert(end <= contentLen);
    721        fragmentLen = PR_MIN(end, contentLen) - fragmentOffset;
    722 
    723        /* Limit further by the record size limit.  Account for the header. */
    724        fragmentLen = PR_MIN(fragmentLen,
    725                             msg->cwSpec->recordSizeLimit - DTLS_HS_HDR_LEN);
    726 
    727        /* Reduce to the space remaining in the MTU. */
    728        fragmentLen = PR_MIN(fragmentLen,
    729                             ss->ssl3.mtu -           /* MTU estimate. */
    730                                 ss->pendingBuf.len - /* Less any unsent records. */
    731                                 DTLS_MAX_EXPANSION - /* Allow for expansion. */
    732                                 DTLS_HS_HDR_LEN);    /* And the handshake header. */
    733        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        if (fragmentLen >= (DTLS_MAX_MTU - DTLS_HS_HDR_LEN)) {
    738            PORT_Assert(0);
    739            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    740            return SECFailure;
    741        }
    742 
    743        if (fragmentLen == contentLen) {
    744            fragment = msg->data;
    745        } else {
    746            sslBuffer tmp = SSL_BUFFER_FIXED(buf, sizeof(buf));
    747 
    748            /* Construct an appropriate-sized fragment */
    749            /* Type, length, sequence */
    750            rv = sslBuffer_Append(&tmp, msg->data, 6);
    751            if (rv != SECSuccess) {
    752                return SECFailure;
    753            }
    754            /* Offset. */
    755            rv = sslBuffer_AppendNumber(&tmp, fragmentOffset, 3);
    756            if (rv != SECSuccess) {
    757                return SECFailure;
    758            }
    759            /* Length. */
    760            rv = sslBuffer_AppendNumber(&tmp, fragmentLen, 3);
    761            if (rv != SECSuccess) {
    762                return SECFailure;
    763            }
    764            /* Data. */
    765            rv = sslBuffer_Append(&tmp, content + fragmentOffset, fragmentLen);
    766            if (rv != SECSuccess) {
    767                return SECFailure;
    768            }
    769 
    770            fragment = SSL_BUFFER_BASE(&tmp);
    771        }
    772 
    773        /* Record that we are sending first, because encrypting
    774         * increments the sequence number. */
    775        rv = dtls13_RememberFragment(ss, &ss->ssl3.hs.dtlsSentHandshake,
    776                                     msgSeq, fragmentOffset, fragmentLen,
    777                                     msg->cwSpec->epoch,
    778                                     msg->cwSpec->nextSeqNum);
    779        if (rv != SECSuccess) {
    780            return SECFailure;
    781        }
    782 
    783        rv = dtls_SendFragment(ss, msg, fragment,
    784                               fragmentLen + DTLS_HS_HDR_LEN);
    785        if (rv != SECSuccess) {
    786            return SECFailure;
    787        }
    788 
    789        fragmentWritten = PR_TRUE;
    790        fragmentOffset += fragmentLen;
    791    } while (fragmentOffset < contentLen);
    792 
    793    if (!fragmentWritten) {
    794        /* Nothing was written if we got here, so the whole message must have
    795         * been acknowledged.  Discard it. */
    796        SSL_TRC(10, ("%d: SSL3[%d]: FragmentHandshake %d: removed",
    797                     SSL_GETPID(), ss->fd, msgSeq));
    798        PR_REMOVE_LINK(&msg->link);
    799        dtls_FreeHandshakeMessage(msg);
    800    }
    801 
    802    return SECSuccess;
    803 }
    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 {
    817    SECStatus rv = SECSuccess;
    818    PRCList *msg_p;
    819 
    820    SSL_TRC(10, ("%d: SSL3[%d]: dtls_TransmitMessageFlight",
    821                 SSL_GETPID(), ss->fd));
    822 
    823    ssl_GetXmitBufLock(ss);
    824    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    PORT_Assert(!ss->pendingBuf.len);
    833 
    834    for (msg_p = PR_LIST_HEAD(&ss->ssl3.hs.lastMessageFlight);
    835         msg_p != &ss->ssl3.hs.lastMessageFlight;) {
    836        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        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        if (msg->type == ssl_ct_handshake) {
    847            rv = dtls_FragmentHandshake(ss, msg);
    848        } else {
    849            PORT_Assert(!tls13_MaybeTls13(ss));
    850            rv = dtls_SendFragment(ss, msg, msg->data, msg->len);
    851        }
    852        if (rv != SECSuccess) {
    853            break;
    854        }
    855    }
    856 
    857    /* Finally, flush any data that wasn't flushed already. */
    858    if (rv == SECSuccess) {
    859        rv = dtls_SendSavedWriteData(ss);
    860    }
    861 
    862    /* Give up the locks */
    863    ssl_ReleaseSpecReadLock(ss);
    864    ssl_ReleaseXmitBufLock(ss);
    865 
    866    return rv;
    867 }
    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 {
    878    PRInt32 sent;
    879 
    880    sent = ssl_SendSavedWriteData(ss);
    881    if (sent < 0)
    882        return SECFailure;
    883 
    884    /* We should always have complete writes b/c datagram sockets
    885     * don't really block */
    886    if (ss->pendingBuf.len > 0) {
    887        ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
    888        return SECFailure;
    889    }
    890 
    891    /* Update the largest message sent so we can adjust the MTU
    892     * estimate if necessary */
    893    if (sent > ss->ssl3.hs.maxMessageSent)
    894        ss->ssl3.hs.maxMessageSent = sent;
    895 
    896    return SECSuccess;
    897 }
    898 
    899 void
    900 dtls_InitTimers(sslSocket *ss)
    901 {
    902    unsigned int i;
    903    dtlsTimer **timers[PR_ARRAY_SIZE(ss->ssl3.hs.timers)] = {
    904        &ss->ssl3.hs.rtTimer,
    905        &ss->ssl3.hs.ackTimer,
    906        &ss->ssl3.hs.hdTimer
    907    };
    908    static const char *timerLabels[] = {
    909        "retransmit", "ack", "holddown"
    910    };
    911 
    912    PORT_Assert(PR_ARRAY_SIZE(timers) == PR_ARRAY_SIZE(timerLabels));
    913    for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
    914        *timers[i] = &ss->ssl3.hs.timers[i];
    915        ss->ssl3.hs.timers[i].label = timerLabels[i];
    916    }
    917 }
    918 
    919 SECStatus
    920 dtls_StartTimer(sslSocket *ss, dtlsTimer *timer, PRUint32 time, DTLSTimerCb cb)
    921 {
    922    PORT_Assert(timer->cb == NULL);
    923 
    924    SSL_TRC(10, ("%d: SSL3[%d]: %s dtls_StartTimer %s timeout=%d",
    925                 SSL_GETPID(), ss->fd, SSL_ROLE(ss), timer->label, time));
    926 
    927    timer->started = PR_IntervalNow();
    928    timer->timeout = time;
    929    timer->cb = cb;
    930    return SECSuccess;
    931 }
    932 
    933 SECStatus
    934 dtls_RestartTimer(sslSocket *ss, dtlsTimer *timer)
    935 {
    936    timer->started = PR_IntervalNow();
    937    return SECSuccess;
    938 }
    939 
    940 PRBool
    941 dtls_TimerActive(sslSocket *ss, dtlsTimer *timer)
    942 {
    943    return timer->cb != NULL;
    944 }
    945 
    946 /* Start a timer for retransmission. */
    947 static SECStatus
    948 dtls_StartRetransmitTimer(sslSocket *ss)
    949 {
    950    dtlsTimer *timer = ss->ssl3.hs.rtTimer;
    951    PRUint32 timeout = DTLS_RETRANSMIT_INITIAL_MS;
    952 
    953    if (dtls_TimerActive(ss, timer)) {
    954        SSL_TRC(10, ("%d: SSL3[%d]: %s dtls timer %s is already active, restarting. New timeout is %d",
    955                     SSL_GETPID(), ss->fd, SSL_ROLE(ss),
    956                     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        (void)dtls_RestartTimer(ss, timer);
    963        ss->ssl3.hs.rtRetries = 0;
    964        timer->timeout = timeout;
    965        return SECSuccess;
    966    }
    967 
    968    ss->ssl3.hs.rtRetries = 0;
    969    return dtls_StartTimer(ss, timer,
    970                           timeout,
    971                           dtls_RetransmitTimerExpiredCb);
    972 }
    973 
    974 /* Start a timer for holding an old cipher spec. */
    975 SECStatus
    976 dtls_StartHolddownTimer(sslSocket *ss)
    977 {
    978    /* DTLS1.3 starts the timer without calling this function, see tls13_ServerHandleFinished.*/
    979    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
    980    return dtls_StartTimer(ss, ss->ssl3.hs.hdTimer,
    981                           DTLS_RETRANSMIT_FINISHED_MS,
    982                           dtls_FinishedTimerCb);
    983 }
    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 {
    994    SSL_TRC(30, ("%d: SSL3[%d]: %s dtls_CancelTimer %s",
    995                 SSL_GETPID(), ss->fd, SSL_ROLE(ss),
    996                 timer->label));
    997 
    998    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
    999 
   1000    timer->cb = NULL;
   1001 }
   1002 
   1003 static void
   1004 dtls_CancelAllTimers(sslSocket *ss)
   1005 {
   1006    unsigned int i;
   1007 
   1008    for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
   1009        dtls_CancelTimer(ss, &ss->ssl3.hs.timers[i]);
   1010    }
   1011 }
   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 {
   1020    unsigned int i;
   1021    SSL_TRC(30, ("%d: SSL3[%d]: dtls_CheckTimer (%s)",
   1022                 SSL_GETPID(), ss->fd, ss->sec.isServer ? "server" : "client"));
   1023 
   1024    ssl_GetSSL3HandshakeLock(ss);
   1025 
   1026    for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
   1027        dtlsTimer *timer = &ss->ssl3.hs.timers[i];
   1028        if (!timer->cb) {
   1029            continue;
   1030        }
   1031 
   1032        if ((PR_IntervalNow() - timer->started) >=
   1033            PR_MillisecondsToInterval(timer->timeout)) {
   1034            /* Timer has expired */
   1035            DTLSTimerCb cb = timer->cb;
   1036 
   1037            SSL_TRC(10, ("%d: SSL3[%d]: %s firing timer %s",
   1038                         SSL_GETPID(), ss->fd, SSL_ROLE(ss),
   1039                         timer->label));
   1040 
   1041            /* Cancel the timer so that we can call the CB safely */
   1042            dtls_CancelTimer(ss, timer);
   1043 
   1044            /* Now call the CB */
   1045            cb(ss);
   1046        }
   1047    }
   1048    ssl_ReleaseSSL3HandshakeLock(ss);
   1049 }
   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 {
   1059    dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
   1060 }
   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 {
   1073    /* Skip this if we are handling a second ClientHello. */
   1074    if (ss->ssl3.hs.helloRetry) {
   1075        return;
   1076    }
   1077    PORT_Assert((ss->version < SSL_LIBRARY_VERSION_TLS_1_3));
   1078    dtls_CancelAllTimers(ss);
   1079    dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
   1080    ss->ssl3.hs.sendMessageSeq = 0;
   1081    ss->ssl3.hs.recvMessageSeq = 0;
   1082 }
   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 {
   1098    int i;
   1099 
   1100    if (advertised == 0) {
   1101        ss->ssl3.mtu = COMMON_MTU_VALUES[0];
   1102        SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu));
   1103        return;
   1104    }
   1105 
   1106    for (i = 0; i < PR_ARRAY_SIZE(COMMON_MTU_VALUES); i++) {
   1107        if (COMMON_MTU_VALUES[i] <= advertised) {
   1108            ss->ssl3.mtu = COMMON_MTU_VALUES[i];
   1109            SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu));
   1110            return;
   1111        }
   1112    }
   1113 
   1114    /* Fallback */
   1115    ss->ssl3.mtu = COMMON_MTU_VALUES[PR_ARRAY_SIZE(COMMON_MTU_VALUES) - 1];
   1116    SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu));
   1117 }
   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 {
   1126    int errCode = SSL_ERROR_RX_MALFORMED_HELLO_VERIFY_REQUEST;
   1127    SECStatus rv;
   1128    SSL3ProtocolVersion temp;
   1129    SSL3AlertDescription desc = illegal_parameter;
   1130 
   1131    SSL_TRC(3, ("%d: SSL3[%d]: handle hello_verify_request handshake",
   1132                SSL_GETPID(), ss->fd));
   1133    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
   1134    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   1135 
   1136    if (ss->ssl3.hs.ws != wait_server_hello) {
   1137        errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST;
   1138        desc = unexpected_message;
   1139        goto alert_loser;
   1140    }
   1141 
   1142    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    rv = ssl_ClientReadVersion(ss, &b, &length, &temp);
   1158    if (rv != SECSuccess) {
   1159        goto loser; /* alert has been sent */
   1160    }
   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    rv = ssl3_ConsumeHandshakeVariable(ss, &ss->ssl3.hs.cookie, 1, &b, &length);
   1166    if (rv != SECSuccess) {
   1167        goto loser; /* alert has been sent */
   1168    }
   1169    if (ss->ssl3.hs.cookie.len > DTLS_COOKIE_BYTES) {
   1170        desc = decode_error;
   1171        goto alert_loser; /* malformed. */
   1172    }
   1173 
   1174    ssl_GetXmitBufLock(ss); /*******************************/
   1175 
   1176    /* Now re-send the client hello */
   1177    rv = ssl3_SendClientHello(ss, client_hello_retransmit);
   1178 
   1179    ssl_ReleaseXmitBufLock(ss); /*******************************/
   1180 
   1181    if (rv == SECSuccess)
   1182        return rv;
   1183 
   1184 alert_loser:
   1185    (void)SSL3_SendAlert(ss, alert_fatal, desc);
   1186 
   1187 loser:
   1188    ssl_MapLowLevelError(errCode);
   1189    return SECFailure;
   1190 }
   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 {
   1201    PORT_Memset(records->data, 0, sizeof(records->data));
   1202    records->left = 0;
   1203    records->right = DTLS_RECVD_RECORDS_WINDOW - 1;
   1204 }
   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 {
   1217    PRUint64 offset;
   1218 
   1219    /* Out of range to the left */
   1220    if (seq < records->left) {
   1221        return -1;
   1222    }
   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    if (seq > records->right)
   1228        return 0;
   1229 
   1230    offset = seq % DTLS_RECVD_RECORDS_WINDOW;
   1231 
   1232    return !!(records->data[offset / 8] & (1 << (offset % 8)));
   1233 }
   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 {
   1242    PRUint64 offset;
   1243 
   1244    if (seq < records->left)
   1245        return;
   1246 
   1247    if (seq > records->right) {
   1248        sslSequenceNumber new_left;
   1249        sslSequenceNumber new_right;
   1250        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        new_right = seq | 0x07;
   1264        new_left = (new_right - DTLS_RECVD_RECORDS_WINDOW) + 1;
   1265 
   1266        if (new_right > records->right + DTLS_RECVD_RECORDS_WINDOW) {
   1267            PORT_Memset(records->data, 0, sizeof(records->data));
   1268        } else {
   1269            for (right = records->right + 8; right <= new_right; right += 8) {
   1270                offset = right % DTLS_RECVD_RECORDS_WINDOW;
   1271                records->data[offset / 8] = 0;
   1272            }
   1273        }
   1274 
   1275        records->right = new_right;
   1276        records->left = new_left;
   1277    }
   1278 
   1279    offset = seq % DTLS_RECVD_RECORDS_WINDOW;
   1280 
   1281    records->data[offset / 8] |= (1 << (offset % 8));
   1282 }
   1283 
   1284 SECStatus
   1285 DTLS_GetHandshakeTimeout(PRFileDesc *socket, PRIntervalTime *timeout)
   1286 {
   1287    sslSocket *ss = NULL;
   1288    PRBool found = PR_FALSE;
   1289    PRIntervalTime now = PR_IntervalNow();
   1290    PRIntervalTime to;
   1291    unsigned int i;
   1292 
   1293    *timeout = PR_INTERVAL_NO_TIMEOUT;
   1294 
   1295    ss = ssl_FindSocket(socket);
   1296 
   1297    if (!ss) {
   1298        PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1299        return SECFailure;
   1300    }
   1301 
   1302    if (!IS_DTLS(ss)) {
   1303        PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1304        return SECFailure;
   1305    }
   1306 
   1307    for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
   1308        PRIntervalTime elapsed;
   1309        PRIntervalTime desired;
   1310        dtlsTimer *timer = &ss->ssl3.hs.timers[i];
   1311 
   1312        if (!timer->cb) {
   1313            continue;
   1314        }
   1315        found = PR_TRUE;
   1316 
   1317        elapsed = now - timer->started;
   1318        desired = PR_MillisecondsToInterval(timer->timeout);
   1319        if (elapsed > desired) {
   1320            /* Timer expired */
   1321            *timeout = PR_INTERVAL_NO_WAIT;
   1322            return SECSuccess;
   1323        } else {
   1324            to = desired - elapsed;
   1325        }
   1326 
   1327        if (*timeout > to) {
   1328            *timeout = to;
   1329        }
   1330    }
   1331 
   1332    if (!found) {
   1333        PORT_SetError(SSL_ERROR_NO_TIMERS_FOUND);
   1334        return SECFailure;
   1335    }
   1336 
   1337    return SECSuccess;
   1338 }
   1339 
   1340 PRBool
   1341 dtls_IsLongHeader(SSL3ProtocolVersion version, PRUint8 firstOctet)
   1342 {
   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    return PR_TRUE;
   1350 #endif
   1351 }
   1352 
   1353 PRBool
   1354 dtls_IsDtls13Ciphertext(SSL3ProtocolVersion version, PRUint8 firstOctet)
   1355 {
   1356    // Allow no version in case we haven't negotiated one yet.
   1357    return (version == 0 || version >= SSL_LIBRARY_VERSION_TLS_1_3) &&
   1358           (firstOctet & 0xe0) == 0x20;
   1359 }
   1360 
   1361 DTLSEpoch
   1362 dtls_ReadEpoch(const SSL3ProtocolVersion version, const DTLSEpoch specEpoch, const PRUint8 *hdr)
   1363 {
   1364    if (dtls_IsLongHeader(version, hdr[0])) {
   1365        return ((DTLSEpoch)hdr[3] << 8) | hdr[4];
   1366    }
   1367 
   1368    DTLSEpoch epoch = (specEpoch & ~3) | (hdr[0] & 3);
   1369    /* The epoch cannot be higher than the current read epoch,
   1370        though guard against underflow. */
   1371    if (epoch > specEpoch && epoch > 4) {
   1372        epoch -= 4;
   1373    }
   1374 
   1375    return epoch;
   1376 }
   1377 
   1378 static sslSequenceNumber
   1379 dtls_ReadSequenceNumber(const ssl3CipherSpec *spec, const PRUint8 *hdr)
   1380 {
   1381    sslSequenceNumber cap;
   1382    sslSequenceNumber partial;
   1383    sslSequenceNumber seqNum;
   1384    sslSequenceNumber mask;
   1385 
   1386    if (dtls_IsLongHeader(spec->version, hdr[0])) {
   1387        static const unsigned int seqNumOffset = 5; /* type, version, epoch */
   1388        static const unsigned int seqNumLength = 6;
   1389        sslReader r = SSL_READER(hdr + seqNumOffset, seqNumLength);
   1390        (void)sslRead_ReadNumber(&r, seqNumLength, &seqNum);
   1391        return seqNum;
   1392    }
   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    if (hdr[0] & 0x08) {
   1404        cap = spec->nextSeqNum + (1ULL << 15);
   1405        partial = (((sslSequenceNumber)hdr[1]) << 8) |
   1406                  (sslSequenceNumber)hdr[2];
   1407        mask = (1ULL << 16) - 1;
   1408    } else {
   1409        cap = spec->nextSeqNum + (1ULL << 7);
   1410        partial = (sslSequenceNumber)hdr[1];
   1411        mask = (1ULL << 8) - 1;
   1412    }
   1413    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    if ((partial > (cap & mask)) && (seqNum > mask)) {
   1418        seqNum -= mask + 1;
   1419    }
   1420    return seqNum;
   1421 }
   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 {
   1440    sslSequenceNumber seqNum = dtls_ReadSequenceNumber(spec, cText->hdr);
   1441    if (dtls_RecordGetRecvd(&spec->recvdRecords, seqNum) != 0) {
   1442        SSL_TRC(10, ("%d: SSL3[%d]: dtls_IsRelevant, rejecting "
   1443                     "potentially replayed packet",
   1444                     SSL_GETPID(), ss->fd));
   1445        return PR_FALSE;
   1446    }
   1447 
   1448    *seqNumOut = seqNum;
   1449    return PR_TRUE;
   1450 }
   1451 
   1452 void
   1453 dtls_ReceivedFirstMessageInFlight(sslSocket *ss)
   1454 {
   1455    if (!IS_DTLS(ss))
   1456        return;
   1457 
   1458    /* At this point we are advancing our state machine, so we can free our last
   1459     * flight of messages. */
   1460    if (ss->ssl3.hs.ws != idle_handshake ||
   1461        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        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        dtls_CancelTimer(ss, ss->ssl3.hs.rtTimer);
   1470        if (ss->ssl3.hs.rtRetries == 0) {
   1471            ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS;
   1472        }
   1473    }
   1474 
   1475    /* Empty the ACK queue (TLS 1.3 only). */
   1476    ssl_ClearPRCList(&ss->ssl3.hs.dtlsRcvdHandshake, NULL);
   1477 }