Coverage Report

Created: 2025-04-22 06:18

/src/nss/lib/ssl/ssl3gthr.c
Line
Count
Source (jump to first uncovered line)
1
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
/*
3
 * Gather (Read) entire SSL3 records from socket into buffer.
4
 *
5
 * This Source Code Form is subject to the terms of the Mozilla Public
6
 * License, v. 2.0. If a copy of the MPL was not distributed with this
7
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8
9
#include "cert.h"
10
#include "ssl.h"
11
#include "sslimpl.h"
12
#include "sslproto.h"
13
#include "ssl3prot.h"
14
15
struct ssl2GatherStr {
16
    /* true when ssl3_GatherData encounters an SSLv2 handshake */
17
    PRBool isV2;
18
19
    /* number of bytes of padding appended to the message content */
20
    PRUint8 padding;
21
};
22
23
typedef struct ssl2GatherStr ssl2Gather;
24
25
/* Caller should hold RecvBufLock. */
26
SECStatus
27
ssl3_InitGather(sslGather *gs)
28
19.4k
{
29
19.4k
    gs->state = GS_INIT;
30
19.4k
    gs->writeOffset = 0;
31
19.4k
    gs->readOffset = 0;
32
19.4k
    gs->dtlsPacketOffset = 0;
33
19.4k
    gs->dtlsPacket.len = 0;
34
19.4k
    gs->rejectV2Records = PR_FALSE;
35
    /* Allocate plaintext buffer to maximum possibly needed size. It needs to
36
     * be larger than recordSizeLimit for TLS 1.0 and 1.1 compatability.
37
     * The TLS 1.2 ciphertext is larger than the TLS 1.3 ciphertext. */
38
19.4k
    return sslBuffer_Grow(&gs->buf, TLS_1_2_MAX_CTEXT_LENGTH);
39
19.4k
}
40
41
/* Caller must hold RecvBufLock. */
42
void
43
ssl3_DestroyGather(sslGather *gs)
44
9.71k
{
45
9.71k
    if (gs) { /* the PORT_*Free functions check for NULL pointers. */
46
9.71k
        PORT_ZFree(gs->buf.buf, gs->buf.space);
47
9.71k
        PORT_Free(gs->inbuf.buf);
48
9.71k
        PORT_Free(gs->dtlsPacket.buf);
49
9.71k
    }
50
9.71k
}
51
52
/* Checks whether a given buffer is likely an SSLv3 record header.  */
53
PRBool
54
ssl3_isLikelyV3Hello(const unsigned char *buf)
55
0
{
56
    /* Even if this was a V2 record header we couldn't possibly parse it
57
     * correctly as the second bit denotes a vaguely-defined security escape. */
58
0
    if (buf[0] & 0x40) {
59
0
        return PR_TRUE;
60
0
    }
61
62
    /* Check for a typical V3 record header. */
63
0
    return (PRBool)(buf[0] >= ssl_ct_change_cipher_spec &&
64
0
                    buf[0] <= ssl_ct_application_data &&
65
0
                    buf[1] == MSB(SSL_LIBRARY_VERSION_3_0));
66
0
}
67
68
/*
69
 * Attempt to read in an entire SSL3 record.
70
 * Blocks here for blocking sockets, otherwise returns -1 with
71
 *  PR_WOULD_BLOCK_ERROR when socket would block.
72
 *
73
 * returns  1 if received a complete SSL3 record.
74
 * returns  0 if recv returns EOF
75
 * returns -1 if recv returns < 0
76
 *  (The error value may have already been set to PR_WOULD_BLOCK_ERROR)
77
 *
78
 * Caller must hold the recv buf lock.
79
 *
80
 * The Gather state machine has 3 states:  GS_INIT, GS_HEADER, GS_DATA.
81
 * GS_HEADER: waiting for the 5-byte SSL3 record header to come in.
82
 * GS_DATA:   waiting for the body of the SSL3 record   to come in.
83
 *
84
 * This loop returns when either
85
 *      (a) an error or EOF occurs,
86
 *  (b) PR_WOULD_BLOCK_ERROR,
87
 *  (c) data (entire SSL3 record) has been received.
88
 */
89
static int
90
ssl3_GatherData(sslSocket *ss, sslGather *gs, int flags, ssl2Gather *ssl2gs)
91
589k
{
92
589k
    unsigned char *bp;
93
589k
    unsigned char *lbp;
94
589k
    int nb;
95
589k
    int err;
96
589k
    int rv = 1;
97
589k
    PRUint8 v2HdrLength = 0;
98
99
589k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
100
589k
    if (gs->state == GS_INIT) {
101
589k
        gs->state = GS_HEADER;
102
589k
        gs->remainder = 5;
103
589k
        gs->offset = 0;
104
589k
        gs->writeOffset = 0;
105
589k
        gs->readOffset = 0;
106
589k
        gs->inbuf.len = 0;
107
589k
    }
108
109
589k
    lbp = gs->inbuf.buf;
110
1.16M
    for (;;) {
111
1.16M
        SSL_TRC(30, ("%d: SSL3[%d]: gather state %d (need %d more)",
112
1.16M
                     SSL_GETPID(), ss->fd, gs->state, gs->remainder));
113
1.16M
        bp = ((gs->state != GS_HEADER) ? lbp : gs->hdr) + gs->offset;
114
1.16M
        nb = ssl_DefRecv(ss, bp, gs->remainder, flags);
115
116
1.16M
        if (nb > 0) {
117
1.16M
            PRINT_BUF(60, (ss, "raw gather data:", bp, nb));
118
1.16M
        } else if (nb == 0) {
119
            /* EOF */
120
6.10k
            SSL_TRC(30, ("%d: SSL3[%d]: EOF", SSL_GETPID(), ss->fd));
121
6.10k
            rv = 0;
122
6.10k
            break;
123
6.10k
        } else /* if (nb < 0) */ {
124
0
            SSL_DBG(("%d: SSL3[%d]: recv error %d", SSL_GETPID(), ss->fd,
125
0
                     PR_GetError()));
126
0
            rv = SECFailure;
127
0
            break;
128
0
        }
129
130
1.16M
        PORT_Assert((unsigned int)nb <= gs->remainder);
131
1.16M
        if ((unsigned int)nb > gs->remainder) {
132
            /* ssl_DefRecv is misbehaving!  this error is fatal to SSL. */
133
0
            gs->state = GS_INIT; /* so we don't crash next time */
134
0
            rv = SECFailure;
135
0
            break;
136
0
        }
137
138
1.16M
        gs->offset += nb;
139
1.16M
        gs->remainder -= nb;
140
1.16M
        if (gs->state == GS_DATA)
141
575k
            gs->inbuf.len += nb;
142
143
        /* if there's more to go, read some more. */
144
1.16M
        if (gs->remainder > 0) {
145
1.24k
            continue;
146
1.24k
        }
147
148
        /* have received entire record header, or entire record. */
149
1.15M
        switch (gs->state) {
150
584k
            case GS_HEADER:
151
                /* Check for SSLv2 handshakes. Always assume SSLv3 on clients,
152
                 * support SSLv2 handshakes only when ssl2gs != NULL.
153
                 * Always assume v3 after we received the first record. */
154
584k
                if (!ssl2gs ||
155
584k
                    ss->gs.rejectV2Records ||
156
584k
                    ssl3_isLikelyV3Hello(gs->hdr)) {
157
                    /* Should have a non-SSLv2 record header in gs->hdr. Extract
158
                     * the length of the following encrypted data, and then
159
                     * read in the rest of the record into gs->inbuf. */
160
584k
                    gs->remainder = (gs->hdr[3] << 8) | gs->hdr[4];
161
584k
                    gs->hdrLen = SSL3_RECORD_HEADER_LENGTH;
162
584k
                } else {
163
                    /* Probably an SSLv2 record header. No need to handle any
164
                     * security escapes (gs->hdr[0] & 0x40) as we wouldn't get
165
                     * here if one was set. See ssl3_isLikelyV3Hello(). */
166
0
                    gs->remainder = ((gs->hdr[0] & 0x7f) << 8) | gs->hdr[1];
167
0
                    ssl2gs->isV2 = PR_TRUE;
168
0
                    v2HdrLength = 2;
169
170
                    /* Is it a 3-byte header with padding? */
171
0
                    if (!(gs->hdr[0] & 0x80)) {
172
0
                        ssl2gs->padding = gs->hdr[2];
173
0
                        v2HdrLength++;
174
0
                    }
175
0
                }
176
177
                /* If it is NOT an SSLv2 header */
178
584k
                if (!v2HdrLength) {
179
                    /* Check if default RFC specified max ciphertext/record
180
                     * limits are respected. Checks for used record size limit
181
                     * extension boundaries are done in
182
                     * ssl3con.c/ssl3_HandleRecord() for tls and dtls records.
183
                     *
184
                     * -> For TLS 1.2 records MUST NOT be longer than
185
                     * 2^14 + 2048 bytes.
186
                     * -> For TLS 1.3 records MUST NOT exceed 2^14 + 256 bytes.
187
                     * -> For older versions this MAY be enforced, we do it.
188
                     * [RFC8446 Section 5.2, RFC5246 Section 6.2.3]. */
189
584k
                    if (gs->remainder > TLS_1_2_MAX_CTEXT_LENGTH ||
190
584k
                        (gs->remainder > TLS_1_3_MAX_CTEXT_LENGTH &&
191
583k
                         ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)) {
192
279
                        SSL3_SendAlert(ss, alert_fatal, record_overflow);
193
279
                        gs->state = GS_INIT;
194
279
                        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
195
279
                        return SECFailure;
196
279
                    }
197
584k
                }
198
199
583k
                gs->state = GS_DATA;
200
583k
                gs->offset = 0;
201
583k
                gs->inbuf.len = 0;
202
203
583k
                if (gs->remainder > gs->inbuf.space) {
204
575k
                    err = sslBuffer_Grow(&gs->inbuf, gs->remainder);
205
575k
                    if (err) { /* realloc has set error code to no mem. */
206
0
                        return err;
207
0
                    }
208
575k
                    lbp = gs->inbuf.buf;
209
575k
                }
210
211
                /* When we encounter an SSLv2 hello we've read 2 or 3 bytes too
212
                 * many into the gs->hdr[] buffer. Copy them over into inbuf so
213
                 * that we can properly process the hello record later. */
214
583k
                if (v2HdrLength) {
215
                    /* Reject v2 records that don't even carry enough data to
216
                     * resemble a valid ClientHello header. */
217
0
                    if (gs->remainder < SSL_HL_CLIENT_HELLO_HBYTES) {
218
0
                        SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
219
0
                        PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
220
0
                        return SECFailure;
221
0
                    }
222
223
0
                    PORT_Assert(lbp);
224
0
                    gs->inbuf.len = 5 - v2HdrLength;
225
0
                    PORT_Memcpy(lbp, gs->hdr + v2HdrLength, gs->inbuf.len);
226
0
                    gs->remainder -= gs->inbuf.len;
227
0
                    lbp += gs->inbuf.len;
228
0
                }
229
230
583k
                if (gs->remainder > 0) {
231
575k
                    break; /* End this case.  Continue around the loop. */
232
575k
                }
233
234
                /* FALL THROUGH if (gs->remainder == 0) as we just received
235
                 * an empty record and there's really no point in calling
236
                 * ssl_DefRecv() with buf=NULL and len=0. */
237
238
583k
            case GS_DATA:
239
                /*
240
                ** SSL3 record has been completely received.
241
                */
242
583k
                SSL_TRC(10, ("%d: SSL[%d]: got record of %d bytes",
243
583k
                             SSL_GETPID(), ss->fd, gs->inbuf.len));
244
245
                /* reject any v2 records from now on */
246
583k
                ss->gs.rejectV2Records = PR_TRUE;
247
248
583k
                gs->state = GS_INIT;
249
583k
                return 1;
250
1.15M
        }
251
1.15M
    }
252
253
6.10k
    return rv;
254
589k
}
255
256
/*
257
 * Read in an entire DTLS record.
258
 *
259
 * Blocks here for blocking sockets, otherwise returns -1 with
260
 *  PR_WOULD_BLOCK_ERROR when socket would block.
261
 *
262
 * This is simpler than SSL because we are reading on a datagram socket
263
 * and datagrams must contain >=1 complete records.
264
 *
265
 * returns  1 if received a complete DTLS record.
266
 * returns  0 if recv returns EOF
267
 * returns -1 if recv returns < 0
268
 *  (The error value may have already been set to PR_WOULD_BLOCK_ERROR)
269
 *
270
 * Caller must hold the recv buf lock.
271
 *
272
 * This loop returns when either
273
 *      (a) an error or EOF occurs,
274
 *  (b) PR_WOULD_BLOCK_ERROR,
275
 *  (c) data (entire DTLS record) has been received.
276
 */
277
static int
278
dtls_GatherData(sslSocket *ss, sslGather *gs, int flags)
279
0
{
280
0
    int nb;
281
0
    PRUint8 contentType;
282
0
    unsigned int headerLen;
283
0
    SECStatus rv = SECSuccess;
284
0
    PRBool dtlsLengthPresent = PR_TRUE;
285
286
0
    SSL_TRC(30, ("dtls_GatherData"));
287
288
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
289
290
0
    gs->state = GS_HEADER;
291
0
    gs->offset = 0;
292
293
0
    if (gs->dtlsPacketOffset == gs->dtlsPacket.len) { /* No data left */
294
0
        gs->dtlsPacketOffset = 0;
295
0
        gs->dtlsPacket.len = 0;
296
297
        /* Resize to the maximum possible size so we can fit a full datagram.
298
         * This leads to record_overflow errors if records/ciphertexts greater
299
         * than the buffer (= maximum record) size are to be received.
300
         * DTLS Record errors are dropped silently. [RFC6347, Section 4.1.2.7].
301
         * Checks for record size limit extension boundaries are performed in
302
         * ssl3con.c/ssl3_HandleRecord() for tls and dtls records.
303
         *
304
         * -> For TLS 1.2 records MUST NOT be longer than 2^14 + 2048 bytes.
305
         * -> For TLS 1.3 records MUST NOT exceed 2^14 + 256 bytes.
306
         * -> For older versions this MAY be enforced, we do it.
307
         * [RFC8446 Section 5.2, RFC5246 Section 6.2.3]. */
308
0
        if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_2) {
309
0
            if (gs->dtlsPacket.space < DTLS_1_2_MAX_PACKET_LENGTH) {
310
0
                rv = sslBuffer_Grow(&gs->dtlsPacket, DTLS_1_2_MAX_PACKET_LENGTH);
311
0
            }
312
0
        } else { /* version >= TLS 1.3 */
313
0
            if (gs->dtlsPacket.space != DTLS_1_3_MAX_PACKET_LENGTH) {
314
                /* During Hello and version negotiation older DTLS versions with
315
                 * greater possible packets are used. The buffer must therefore
316
                 * be "truncated" by clearing and reallocating it */
317
0
                sslBuffer_Clear(&gs->dtlsPacket);
318
0
                rv = sslBuffer_Grow(&gs->dtlsPacket, DTLS_1_3_MAX_PACKET_LENGTH);
319
0
            }
320
0
        }
321
322
0
        if (rv != SECSuccess) {
323
0
            return -1; /* Code already set. */
324
0
        }
325
326
        /* recv() needs to read a full datagram at a time */
327
0
        nb = ssl_DefRecv(ss, gs->dtlsPacket.buf, gs->dtlsPacket.space, flags);
328
0
        if (nb > 0) {
329
0
            PRINT_BUF(60, (ss, "raw gather data:", gs->dtlsPacket.buf, nb));
330
0
        } else if (nb == 0) {
331
            /* EOF */
332
0
            SSL_TRC(30, ("%d: SSL3[%d]: EOF", SSL_GETPID(), ss->fd));
333
0
            return 0;
334
0
        } else /* if (nb < 0) */ {
335
0
            SSL_DBG(("%d: SSL3[%d]: recv error %d", SSL_GETPID(), ss->fd,
336
0
                     PR_GetError()));
337
            /* DTLS Record Errors, including overlong records, are silently
338
             * dropped [RFC6347, Section 4.1.2.7]. */
339
0
            return -1;
340
0
        }
341
342
0
        gs->dtlsPacket.len = nb;
343
0
    }
344
345
0
    contentType = gs->dtlsPacket.buf[gs->dtlsPacketOffset];
346
0
    if (dtls_IsLongHeader(ss->version, contentType)) {
347
0
        headerLen = 13;
348
0
    } else if (contentType == ssl_ct_application_data) {
349
0
        headerLen = 7;
350
0
    } else if (dtls_IsDtls13Ciphertext(ss->version, contentType)) {
351
        /* We don't support CIDs.
352
         *
353
         * This condition is met on all invalid outer content types.
354
         * For lower DTLS versions as well as the inner content types,
355
         * this is checked in ssl3con.c/ssl3_HandleNonApplicationData().
356
         *
357
         * In DTLS generally invalid records SHOULD be silently discarded,
358
         * no alert is sent [RFC6347, Section 4.1.2.7].
359
         */
360
0
        if (contentType & 0x10) {
361
0
            PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
362
0
            gs->dtlsPacketOffset = 0;
363
0
            gs->dtlsPacket.len = 0;
364
0
            return -1;
365
0
        }
366
367
0
        dtlsLengthPresent = (contentType & 0x04) == 0x04;
368
0
        PRUint8 dtlsSeqNoSize = (contentType & 0x08) ? 2 : 1;
369
0
        PRUint8 dtlsLengthBytes = dtlsLengthPresent ? 2 : 0;
370
0
        headerLen = 1 + dtlsSeqNoSize + dtlsLengthBytes;
371
0
    } else {
372
0
        SSL_DBG(("%d: SSL3[%d]: invalid first octet (%d) for DTLS",
373
0
                 SSL_GETPID(), ss->fd, contentType));
374
0
        PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
375
0
        gs->dtlsPacketOffset = 0;
376
0
        gs->dtlsPacket.len = 0;
377
0
        return -1;
378
0
    }
379
380
    /* At this point we should have >=1 complete records lined up in
381
     * dtlsPacket. Read off the header.
382
     */
383
0
    if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < headerLen) {
384
0
        SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet "
385
0
                 "too short to contain header",
386
0
                 SSL_GETPID(), ss->fd));
387
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
388
0
        gs->dtlsPacketOffset = 0;
389
0
        gs->dtlsPacket.len = 0;
390
0
        return -1;
391
0
    }
392
0
    memcpy(gs->hdr, SSL_BUFFER_BASE(&gs->dtlsPacket) + gs->dtlsPacketOffset,
393
0
           headerLen);
394
0
    gs->hdrLen = headerLen;
395
0
    gs->dtlsPacketOffset += headerLen;
396
397
    /* Have received SSL3 record header in gs->hdr. */
398
0
    if (dtlsLengthPresent) {
399
0
        gs->remainder = (gs->hdr[headerLen - 2] << 8) |
400
0
                        gs->hdr[headerLen - 1];
401
0
    } else {
402
0
        gs->remainder = gs->dtlsPacket.len - gs->dtlsPacketOffset;
403
0
    }
404
405
0
    if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < gs->remainder) {
406
0
        SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet too short "
407
0
                 "to contain rest of body",
408
0
                 SSL_GETPID(), ss->fd));
409
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
410
0
        gs->dtlsPacketOffset = 0;
411
0
        gs->dtlsPacket.len = 0;
412
0
        return -1;
413
0
    }
414
415
    /* OK, we have at least one complete packet, copy into inbuf */
416
0
    gs->inbuf.len = 0;
417
0
    rv = sslBuffer_Append(&gs->inbuf,
418
0
                          SSL_BUFFER_BASE(&gs->dtlsPacket) + gs->dtlsPacketOffset,
419
0
                          gs->remainder);
420
0
    if (rv != SECSuccess) {
421
0
        return -1; /* code already set. */
422
0
    }
423
0
    gs->offset = gs->remainder;
424
0
    gs->dtlsPacketOffset += gs->remainder;
425
0
    gs->state = GS_INIT;
426
427
0
    SSL_TRC(20, ("%d: SSL3[%d]: dtls gathered record type=%d len=%d",
428
0
                 SSL_GETPID(), ss->fd, contentType, gs->inbuf.len));
429
0
    return 1;
430
0
}
431
432
/* Gather in a record and when complete, Handle that record.
433
 * Repeat this until the handshake is complete,
434
 * or until application data is available.
435
 *
436
 * Returns  1 when the handshake is completed without error, or
437
 *                 application data is available.
438
 * Returns  0 if ssl3_GatherData hits EOF.
439
 * Returns -1 on read error, or PR_WOULD_BLOCK_ERROR, or handleRecord error.
440
 *
441
 * Called from ssl_GatherRecord1stHandshake       in sslcon.c,
442
 *    and from SSL_ForceHandshake in sslsecur.c
443
 *    and from ssl3_GatherAppDataRecord below (<- DoRecv in sslsecur.c).
444
 *
445
 * Caller must hold the recv buf lock.
446
 */
447
int
448
ssl3_GatherCompleteHandshake(sslSocket *ss, int flags)
449
386k
{
450
386k
    int rv;
451
386k
    SSL3Ciphertext cText;
452
386k
    PRBool keepGoing = PR_TRUE;
453
454
386k
    if (ss->ssl3.fatalAlertSent) {
455
0
        SSL_TRC(3, ("%d: SSL3[%d] Cannot gather data; fatal alert already sent",
456
0
                    SSL_GETPID(), ss->fd));
457
0
        PORT_SetError(SSL_ERROR_HANDSHAKE_FAILED);
458
0
        return -1;
459
0
    }
460
461
386k
    SSL_TRC(30, ("%d: SSL3[%d]: ssl3_GatherCompleteHandshake",
462
386k
                 SSL_GETPID(), ss->fd));
463
464
    /* ssl3_HandleRecord may end up eventually calling ssl_FinishHandshake,
465
     * which requires the 1stHandshakeLock, which must be acquired before the
466
     * RecvBufLock.
467
     */
468
386k
    PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
469
386k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
470
471
589k
    do {
472
589k
        PRBool processingEarlyData;
473
474
589k
        ssl_GetSSL3HandshakeLock(ss);
475
476
589k
        processingEarlyData = ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted;
477
478
        /* Without this, we may end up wrongly reporting
479
         * SSL_ERROR_RX_UNEXPECTED_* errors if we receive any records from the
480
         * peer while we are waiting to be restarted.
481
         */
482
589k
        if (ss->ssl3.hs.restartTarget) {
483
0
            ssl_ReleaseSSL3HandshakeLock(ss);
484
0
            PORT_SetError(PR_WOULD_BLOCK_ERROR);
485
0
            return -1;
486
0
        }
487
488
        /* If we have a detached record layer, don't ever gather. */
489
589k
        if (ss->recordWriteCallback) {
490
0
            PRBool done = ss->firstHsDone;
491
0
            ssl_ReleaseSSL3HandshakeLock(ss);
492
0
            if (done) {
493
0
                return 1;
494
0
            }
495
0
            PORT_SetError(PR_WOULD_BLOCK_ERROR);
496
0
            return -1;
497
0
        }
498
499
589k
        ssl_ReleaseSSL3HandshakeLock(ss);
500
501
        /* State for SSLv2 client hello support. */
502
589k
        ssl2Gather ssl2gs = { PR_FALSE, 0 };
503
589k
        ssl2Gather *ssl2gs_ptr = NULL;
504
505
        /* If we're a server and waiting for a client hello, accept v2. */
506
589k
        if (ss->sec.isServer && ss->opt.enableV2CompatibleHello &&
507
589k
            ss->ssl3.hs.ws == wait_client_hello) {
508
0
            ssl2gs_ptr = &ssl2gs;
509
0
        }
510
511
        /* bring in the next sslv3 record. */
512
589k
        if (ss->recvdCloseNotify) {
513
            /* RFC 5246 Section 7.2.1:
514
             *   Any data received after a closure alert is ignored.
515
             */
516
2
            return 0;
517
2
        }
518
519
589k
        if (!IS_DTLS(ss)) {
520
            /* If we're a server waiting for a ClientHello then pass
521
             * ssl2gs to support SSLv2 ClientHello messages. */
522
589k
            rv = ssl3_GatherData(ss, &ss->gs, flags, ssl2gs_ptr);
523
589k
        } else {
524
0
            rv = dtls_GatherData(ss, &ss->gs, flags);
525
526
            /* If we got a would block error, that means that no data was
527
             * available, so we check the timer to see if it's time to
528
             * retransmit */
529
0
            if (rv == SECFailure &&
530
0
                (PORT_GetError() == PR_WOULD_BLOCK_ERROR)) {
531
0
                dtls_CheckTimer(ss);
532
                /* Restore the error in case something succeeded */
533
0
                PORT_SetError(PR_WOULD_BLOCK_ERROR);
534
0
            }
535
0
        }
536
537
589k
        if (rv <= 0) {
538
6.38k
            return rv;
539
6.38k
        }
540
541
583k
        if (ssl2gs.isV2) {
542
0
            rv = ssl3_HandleV2ClientHello(ss, ss->gs.inbuf.buf,
543
0
                                          ss->gs.inbuf.len,
544
0
                                          ssl2gs.padding);
545
0
            if (rv < 0) {
546
0
                return rv;
547
0
            }
548
583k
        } else {
549
            /* decipher it, and handle it if it's a handshake.
550
             * If it's application data, ss->gs.buf will not be empty upon return.
551
             * If it's a change cipher spec, alert, or handshake message,
552
             * ss->gs.buf.len will be 0 when ssl3_HandleRecord returns SECSuccess.
553
             *
554
             * cText only needs to be valid for this next function call, so
555
             * it can borrow gs.hdr.
556
             */
557
583k
            cText.hdr = ss->gs.hdr;
558
583k
            cText.hdrLen = ss->gs.hdrLen;
559
583k
            cText.buf = &ss->gs.inbuf;
560
583k
            rv = ssl3_HandleRecord(ss, &cText);
561
583k
        }
562
563
583k
#ifdef DEBUG
564
        /* In Debug builds free gather ciphertext buffer after each decryption
565
         * for advanced ASAN coverage/utilization. The buffer content has been
566
         * used at this point, ssl3_HandleRecord() and thereby the decryption
567
         * functions are only called from this point of the implementation. */
568
583k
        sslBuffer_Clear(&ss->gs.inbuf);
569
583k
#endif
570
571
583k
        if (rv < 0) {
572
3.32k
            return ss->recvdCloseNotify ? 0 : rv;
573
3.32k
        }
574
579k
        if (ss->gs.buf.len > 0) {
575
            /* We have application data to return to the application. This
576
             * prioritizes returning application data to the application over
577
             * completing any renegotiation handshake we may be doing.
578
             */
579
156k
            PORT_Assert(ss->firstHsDone);
580
156k
            break;
581
156k
        }
582
583
423k
        PORT_Assert(keepGoing);
584
423k
        ssl_GetSSL3HandshakeLock(ss);
585
423k
        if (ss->ssl3.hs.ws == idle_handshake) {
586
            /* We are done with the current handshake so stop trying to
587
             * handshake. Note that it would be safe to test ss->firstHsDone
588
             * instead of ss->ssl3.hs.ws. By testing ss->ssl3.hs.ws instead,
589
             * we prioritize completing a renegotiation handshake over sending
590
             * application data.
591
             */
592
220k
            PORT_Assert(ss->firstHsDone);
593
220k
            PORT_Assert(!ss->ssl3.hs.canFalseStart);
594
220k
            keepGoing = PR_FALSE;
595
220k
        } else if (ss->ssl3.hs.canFalseStart) {
596
            /* Prioritize sending application data over trying to complete
597
             * the handshake if we're false starting.
598
             *
599
             * If we were to do this check at the beginning of the loop instead
600
             * of here, then this function would become be a no-op after
601
             * receiving the ServerHelloDone in the false start case, and we
602
             * would never complete the handshake.
603
             */
604
0
            PORT_Assert(!ss->firstHsDone);
605
606
0
            if (ssl3_WaitingForServerSecondRound(ss)) {
607
0
                keepGoing = PR_FALSE;
608
0
            } else {
609
0
                ss->ssl3.hs.canFalseStart = PR_FALSE;
610
0
            }
611
202k
        } else if (processingEarlyData &&
612
202k
                   ss->ssl3.hs.zeroRttState == ssl_0rtt_done &&
613
202k
                   !PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)) {
614
            /* If we were processing early data and we are no longer, then force
615
             * the handshake to block.  This ensures that early data is
616
             * delivered to the application before the handshake completes. */
617
0
            ssl_ReleaseSSL3HandshakeLock(ss);
618
0
            PORT_SetError(PR_WOULD_BLOCK_ERROR);
619
0
            return -1;
620
0
        }
621
423k
        ssl_ReleaseSSL3HandshakeLock(ss);
622
423k
    } while (keepGoing);
623
624
    /* Service the DTLS timer so that the post-handshake timers
625
     * fire. */
626
376k
    if (IS_DTLS(ss) && (ss->ssl3.hs.ws == idle_handshake)) {
627
0
        dtls_CheckTimer(ss);
628
0
    }
629
376k
    ss->gs.readOffset = 0;
630
376k
    ss->gs.writeOffset = ss->gs.buf.len;
631
376k
    return 1;
632
386k
}
633
634
/* Repeatedly gather in a record and when complete, Handle that record.
635
 * Repeat this until some application data is received.
636
 *
637
 * Returns  1 when application data is available.
638
 * Returns  0 if ssl3_GatherData hits EOF.
639
 * Returns -1 on read error, or PR_WOULD_BLOCK_ERROR, or handleRecord error.
640
 *
641
 * Called from DoRecv in sslsecur.c
642
 * Caller must hold the recv buf lock.
643
 */
644
int
645
ssl3_GatherAppDataRecord(sslSocket *ss, int flags)
646
159k
{
647
159k
    int rv;
648
649
    /* ssl3_GatherCompleteHandshake requires both of these locks. */
650
159k
    PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
651
159k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
652
653
376k
    do {
654
376k
        rv = ssl3_GatherCompleteHandshake(ss, flags);
655
376k
    } while (rv > 0 && ss->gs.buf.len == 0);
656
657
159k
    return rv;
658
159k
}
659
660
static SECStatus
661
ssl_HandleZeroRttRecordData(sslSocket *ss, const PRUint8 *data, unsigned int len)
662
0
{
663
0
    PORT_Assert(ss->sec.isServer);
664
0
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
665
0
        sslBuffer buf = { CONST_CAST(PRUint8, data), len, len, PR_TRUE };
666
0
        return tls13_HandleEarlyApplicationData(ss, &buf);
667
0
    }
668
0
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored &&
669
0
        ss->ssl3.hs.zeroRttIgnore != ssl_0rtt_ignore_none) {
670
        /* We're ignoring 0-RTT so drop this record quietly. */
671
0
        return SECSuccess;
672
0
    }
673
0
    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
674
0
    return SECFailure;
675
0
}
676
677
/* Ensure that application data in the wrong epoch is blocked. */
678
static PRBool
679
ssl_IsApplicationDataPermitted(sslSocket *ss, PRUint16 epoch)
680
0
{
681
    /* Epoch 0 is never OK. */
682
0
    if (epoch == 0) {
683
0
        return PR_FALSE;
684
0
    }
685
0
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
686
0
        return ss->firstHsDone;
687
0
    }
688
    /* TLS 1.3 application data. */
689
0
    if (epoch >= TrafficKeyApplicationData) {
690
0
        return ss->firstHsDone;
691
0
    }
692
    /* TLS 1.3 early data is server only. Further checks aren't needed
693
     * as those are handled in ssl_HandleZeroRttRecordData. */
694
0
    if (epoch == TrafficKeyEarlyApplicationData) {
695
0
        return ss->sec.isServer;
696
0
    }
697
0
    return PR_FALSE;
698
0
}
699
700
SECStatus
701
SSLExp_RecordLayerData(PRFileDesc *fd, PRUint16 epoch,
702
                       SSLContentType contentType,
703
                       const PRUint8 *data, unsigned int len)
704
0
{
705
0
    SECStatus rv;
706
0
    sslSocket *ss = ssl_FindSocket(fd);
707
0
    if (!ss) {
708
0
        return SECFailure;
709
0
    }
710
0
    if (IS_DTLS(ss) || data == NULL || len == 0) {
711
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
712
0
        return SECFailure;
713
0
    }
714
715
    /* Run any handshake function.  If SSL_RecordLayerData is the only way that
716
     * the handshake is driven, then this is necessary to ensure that
717
     * ssl_BeginClientHandshake or ssl_BeginServerHandshake is called. Note that
718
     * the other function that might be set to ss->handshake,
719
     * ssl3_GatherCompleteHandshake, does nothing when this function is used. */
720
0
    ssl_Get1stHandshakeLock(ss);
721
0
    rv = ssl_Do1stHandshake(ss);
722
0
    if (rv != SECSuccess && PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
723
0
        goto early_loser; /* Rely on the existing code. */
724
0
    }
725
726
0
    if (contentType == ssl_ct_application_data &&
727
0
        !ssl_IsApplicationDataPermitted(ss, epoch)) {
728
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
729
0
        goto early_loser;
730
0
    }
731
732
    /* Then we can validate the epoch. */
733
0
    PRErrorCode epochError;
734
0
    ssl_GetSpecReadLock(ss);
735
0
    if (epoch < ss->ssl3.crSpec->epoch) {
736
0
        epochError = SEC_ERROR_INVALID_ARGS; /* Too c/old. */
737
0
    } else if (epoch > ss->ssl3.crSpec->epoch) {
738
        /* If a TLS 1.3 server is not expecting EndOfEarlyData,
739
         * moving from 1 to 2 is a signal to execute the code
740
         * as though that message had been received. Let that pass. */
741
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
742
0
            ss->opt.suppressEndOfEarlyData &&
743
0
            ss->sec.isServer &&
744
0
            ss->ssl3.crSpec->epoch == TrafficKeyEarlyApplicationData &&
745
0
            epoch == TrafficKeyHandshake) {
746
0
            epochError = 0;
747
0
        } else {
748
0
            epochError = PR_WOULD_BLOCK_ERROR; /* Too warm/new. */
749
0
        }
750
0
    } else {
751
0
        epochError = 0; /* Just right. */
752
0
    }
753
0
    ssl_ReleaseSpecReadLock(ss);
754
0
    if (epochError) {
755
0
        PORT_SetError(epochError);
756
0
        goto early_loser;
757
0
    }
758
759
    /* If the handshake is still running, we need to run that. */
760
0
    rv = ssl_Do1stHandshake(ss);
761
0
    if (rv != SECSuccess && PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
762
0
        goto early_loser;
763
0
    }
764
765
    /* 0-RTT needs its own special handling here. */
766
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
767
0
        epoch == TrafficKeyEarlyApplicationData &&
768
0
        contentType == ssl_ct_application_data) {
769
0
        rv = ssl_HandleZeroRttRecordData(ss, data, len);
770
0
        ssl_Release1stHandshakeLock(ss);
771
0
        return rv;
772
0
    }
773
774
    /* Finally, save the data... */
775
0
    ssl_GetRecvBufLock(ss);
776
0
    rv = sslBuffer_Append(&ss->gs.buf, data, len);
777
0
    if (rv != SECSuccess) {
778
0
        goto loser;
779
0
    }
780
781
    /* ...and process it.  Just saving application data is enough for it to be
782
     * available to PR_Read(). */
783
0
    if (contentType != ssl_ct_application_data) {
784
0
        rv = ssl3_HandleNonApplicationData(ss, contentType, 0, 0, &ss->gs.buf);
785
        /* This occasionally blocks, but that's OK here. */
786
0
        if (rv != SECSuccess && PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
787
0
            goto loser;
788
0
        }
789
0
    }
790
791
0
    ssl_ReleaseRecvBufLock(ss);
792
0
    ssl_Release1stHandshakeLock(ss);
793
0
    return SECSuccess;
794
795
0
loser:
796
    /* Make sure that any data is not used again. */
797
0
    ss->gs.buf.len = 0;
798
0
    ssl_ReleaseRecvBufLock(ss);
799
0
early_loser:
800
0
    ssl_Release1stHandshakeLock(ss);
801
0
    return SECFailure;
802
0
}
803
804
SECStatus
805
SSLExp_GetCurrentEpoch(PRFileDesc *fd, PRUint16 *readEpoch,
806
                       PRUint16 *writeEpoch)
807
0
{
808
0
    sslSocket *ss = ssl_FindSocket(fd);
809
0
    if (!ss) {
810
0
        return SECFailure;
811
0
    }
812
813
0
    ssl_GetSpecReadLock(ss);
814
0
    if (readEpoch) {
815
0
        *readEpoch = ss->ssl3.crSpec->epoch;
816
0
    }
817
0
    if (writeEpoch) {
818
0
        *writeEpoch = ss->ssl3.cwSpec->epoch;
819
0
    }
820
0
    ssl_ReleaseSpecReadLock(ss);
821
0
    return SECSuccess;
822
0
}