ssl3gthr.c (30068B)
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 { 29 gs->state = GS_INIT; 30 gs->writeOffset = 0; 31 gs->readOffset = 0; 32 gs->dtlsPacketOffset = 0; 33 gs->dtlsPacket.len = 0; 34 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 return sslBuffer_Grow(&gs->buf, TLS_1_2_MAX_CTEXT_LENGTH); 39 } 40 41 /* Caller must hold RecvBufLock. */ 42 void 43 ssl3_DestroyGather(sslGather *gs) 44 { 45 if (gs) { /* the PORT_*Free functions check for NULL pointers. */ 46 PORT_ZFree(gs->buf.buf, gs->buf.space); 47 PORT_Free(gs->inbuf.buf); 48 PORT_Free(gs->dtlsPacket.buf); 49 } 50 } 51 52 /* Checks whether a given buffer is likely an SSLv3 record header. */ 53 PRBool 54 ssl3_isLikelyV3Hello(const unsigned char *buf) 55 { 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 if (buf[0] & 0x40) { 59 return PR_TRUE; 60 } 61 62 /* Check for a typical V3 record header. */ 63 return (PRBool)(buf[0] >= ssl_ct_change_cipher_spec && 64 buf[0] <= ssl_ct_application_data && 65 buf[1] == MSB(SSL_LIBRARY_VERSION_3_0)); 66 } 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 { 92 unsigned char *bp; 93 unsigned char *lbp; 94 int nb; 95 int err; 96 int rv = 1; 97 PRUint8 v2HdrLength = 0; 98 99 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 100 if (gs->state == GS_INIT) { 101 gs->state = GS_HEADER; 102 gs->remainder = 5; 103 gs->offset = 0; 104 gs->writeOffset = 0; 105 gs->readOffset = 0; 106 gs->inbuf.len = 0; 107 } 108 109 lbp = gs->inbuf.buf; 110 for (;;) { 111 SSL_TRC(30, ("%d: SSL3[%d]: gather state %d (need %d more)", 112 SSL_GETPID(), ss->fd, gs->state, gs->remainder)); 113 bp = ((gs->state != GS_HEADER) ? lbp : gs->hdr) + gs->offset; 114 nb = ssl_DefRecv(ss, bp, gs->remainder, flags); 115 116 if (nb > 0) { 117 PRINT_BUF(60, (ss, "raw gather data:", bp, nb)); 118 } else if (nb == 0) { 119 /* EOF */ 120 SSL_TRC(30, ("%d: SSL3[%d]: EOF", SSL_GETPID(), ss->fd)); 121 rv = 0; 122 break; 123 } else /* if (nb < 0) */ { 124 SSL_DBG(("%d: SSL3[%d]: recv error %d", SSL_GETPID(), ss->fd, 125 PR_GetError())); 126 rv = SECFailure; 127 break; 128 } 129 130 PORT_Assert((unsigned int)nb <= gs->remainder); 131 if ((unsigned int)nb > gs->remainder) { 132 /* ssl_DefRecv is misbehaving! this error is fatal to SSL. */ 133 gs->state = GS_INIT; /* so we don't crash next time */ 134 rv = SECFailure; 135 break; 136 } 137 138 gs->offset += nb; 139 gs->remainder -= nb; 140 if (gs->state == GS_DATA) 141 gs->inbuf.len += nb; 142 143 /* if there's more to go, read some more. */ 144 if (gs->remainder > 0) { 145 continue; 146 } 147 148 /* have received entire record header, or entire record. */ 149 switch (gs->state) { 150 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 if (!ssl2gs || 155 ss->gs.rejectV2Records || 156 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 gs->remainder = (gs->hdr[3] << 8) | gs->hdr[4]; 161 gs->hdrLen = SSL3_RECORD_HEADER_LENGTH; 162 } 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 gs->remainder = ((gs->hdr[0] & 0x7f) << 8) | gs->hdr[1]; 167 ssl2gs->isV2 = PR_TRUE; 168 v2HdrLength = 2; 169 170 /* Is it a 3-byte header with padding? */ 171 if (!(gs->hdr[0] & 0x80)) { 172 ssl2gs->padding = gs->hdr[2]; 173 v2HdrLength++; 174 } 175 } 176 177 /* If it is NOT an SSLv2 header */ 178 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 if (gs->remainder > TLS_1_2_MAX_CTEXT_LENGTH || 190 (gs->remainder > TLS_1_3_MAX_CTEXT_LENGTH && 191 ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)) { 192 SSL3_SendAlert(ss, alert_fatal, record_overflow); 193 gs->state = GS_INIT; 194 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); 195 return SECFailure; 196 } 197 } 198 199 gs->state = GS_DATA; 200 gs->offset = 0; 201 gs->inbuf.len = 0; 202 203 if (gs->remainder > gs->inbuf.space) { 204 err = sslBuffer_Grow(&gs->inbuf, gs->remainder); 205 if (err) { /* realloc has set error code to no mem. */ 206 return err; 207 } 208 lbp = gs->inbuf.buf; 209 } 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 if (v2HdrLength) { 215 /* Reject v2 records that don't even carry enough data to 216 * resemble a valid ClientHello header. */ 217 if (gs->remainder < SSL_HL_CLIENT_HELLO_HBYTES) { 218 SSL3_SendAlert(ss, alert_fatal, illegal_parameter); 219 PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO); 220 return SECFailure; 221 } 222 223 PORT_Assert(lbp); 224 gs->inbuf.len = 5 - v2HdrLength; 225 PORT_Memcpy(lbp, gs->hdr + v2HdrLength, gs->inbuf.len); 226 gs->remainder -= gs->inbuf.len; 227 lbp += gs->inbuf.len; 228 } 229 230 if (gs->remainder > 0) { 231 break; /* End this case. Continue around the loop. */ 232 } 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 case GS_DATA: 239 /* 240 ** SSL3 record has been completely received. 241 */ 242 SSL_TRC(10, ("%d: SSL[%d]: got record of %d bytes", 243 SSL_GETPID(), ss->fd, gs->inbuf.len)); 244 245 /* reject any v2 records from now on */ 246 ss->gs.rejectV2Records = PR_TRUE; 247 248 gs->state = GS_INIT; 249 return 1; 250 } 251 } 252 253 return rv; 254 } 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 { 280 int nb; 281 PRUint8 contentType; 282 unsigned int headerLen; 283 SECStatus rv = SECSuccess; 284 PRBool dtlsLengthPresent = PR_TRUE; 285 286 SSL_TRC(30, ("dtls_GatherData")); 287 288 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 289 290 gs->state = GS_HEADER; 291 gs->offset = 0; 292 293 if (gs->dtlsPacketOffset == gs->dtlsPacket.len) { /* No data left */ 294 gs->dtlsPacketOffset = 0; 295 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 if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_2) { 309 if (gs->dtlsPacket.space < DTLS_1_2_MAX_PACKET_LENGTH) { 310 rv = sslBuffer_Grow(&gs->dtlsPacket, DTLS_1_2_MAX_PACKET_LENGTH); 311 } 312 } else { /* version >= TLS 1.3 */ 313 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 sslBuffer_Clear(&gs->dtlsPacket); 318 rv = sslBuffer_Grow(&gs->dtlsPacket, DTLS_1_3_MAX_PACKET_LENGTH); 319 } 320 } 321 322 if (rv != SECSuccess) { 323 return -1; /* Code already set. */ 324 } 325 326 /* recv() needs to read a full datagram at a time */ 327 nb = ssl_DefRecv(ss, gs->dtlsPacket.buf, gs->dtlsPacket.space, flags); 328 if (nb > 0) { 329 PRINT_BUF(60, (ss, "raw gather data:", gs->dtlsPacket.buf, nb)); 330 } else if (nb == 0) { 331 /* EOF */ 332 SSL_TRC(30, ("%d: SSL3[%d]: EOF", SSL_GETPID(), ss->fd)); 333 return 0; 334 } else /* if (nb < 0) */ { 335 SSL_DBG(("%d: SSL3[%d]: recv error %d", SSL_GETPID(), ss->fd, 336 PR_GetError())); 337 /* DTLS Record Errors, including overlong records, are silently 338 * dropped [RFC6347, Section 4.1.2.7]. */ 339 return -1; 340 } 341 342 gs->dtlsPacket.len = nb; 343 } 344 345 contentType = gs->dtlsPacket.buf[gs->dtlsPacketOffset]; 346 if (dtls_IsLongHeader(ss->version, contentType)) { 347 headerLen = 13; 348 } else if (contentType == ssl_ct_application_data) { 349 headerLen = 7; 350 } 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 if (contentType & 0x10) { 361 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); 362 gs->dtlsPacketOffset = 0; 363 gs->dtlsPacket.len = 0; 364 return -1; 365 } 366 367 dtlsLengthPresent = (contentType & 0x04) == 0x04; 368 PRUint8 dtlsSeqNoSize = (contentType & 0x08) ? 2 : 1; 369 PRUint8 dtlsLengthBytes = dtlsLengthPresent ? 2 : 0; 370 headerLen = 1 + dtlsSeqNoSize + dtlsLengthBytes; 371 } else { 372 SSL_DBG(("%d: SSL3[%d]: invalid first octet (%d) for DTLS", 373 SSL_GETPID(), ss->fd, contentType)); 374 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); 375 gs->dtlsPacketOffset = 0; 376 gs->dtlsPacket.len = 0; 377 return -1; 378 } 379 380 /* At this point we should have >=1 complete records lined up in 381 * dtlsPacket. Read off the header. 382 */ 383 if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < headerLen) { 384 SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet " 385 "too short to contain header", 386 SSL_GETPID(), ss->fd)); 387 PORT_SetError(PR_WOULD_BLOCK_ERROR); 388 gs->dtlsPacketOffset = 0; 389 gs->dtlsPacket.len = 0; 390 return -1; 391 } 392 memcpy(gs->hdr, SSL_BUFFER_BASE(&gs->dtlsPacket) + gs->dtlsPacketOffset, 393 headerLen); 394 gs->hdrLen = headerLen; 395 gs->dtlsPacketOffset += headerLen; 396 397 /* Have received SSL3 record header in gs->hdr. */ 398 if (dtlsLengthPresent) { 399 gs->remainder = (gs->hdr[headerLen - 2] << 8) | 400 gs->hdr[headerLen - 1]; 401 } else { 402 gs->remainder = gs->dtlsPacket.len - gs->dtlsPacketOffset; 403 } 404 405 if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < gs->remainder) { 406 SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet too short " 407 "to contain rest of body", 408 SSL_GETPID(), ss->fd)); 409 PORT_SetError(PR_WOULD_BLOCK_ERROR); 410 gs->dtlsPacketOffset = 0; 411 gs->dtlsPacket.len = 0; 412 return -1; 413 } 414 415 /* OK, we have at least one complete packet, copy into inbuf */ 416 gs->inbuf.len = 0; 417 rv = sslBuffer_Append(&gs->inbuf, 418 SSL_BUFFER_BASE(&gs->dtlsPacket) + gs->dtlsPacketOffset, 419 gs->remainder); 420 if (rv != SECSuccess) { 421 return -1; /* code already set. */ 422 } 423 gs->offset = gs->remainder; 424 gs->dtlsPacketOffset += gs->remainder; 425 gs->state = GS_INIT; 426 427 SSL_TRC(20, ("%d: SSL3[%d]: dtls gathered record type=%d len=%d", 428 SSL_GETPID(), ss->fd, contentType, gs->inbuf.len)); 429 return 1; 430 } 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 { 450 int rv; 451 SSL3Ciphertext cText; 452 PRBool keepGoing = PR_TRUE; 453 454 if (ss->ssl3.fatalAlertSent) { 455 SSL_TRC(3, ("%d: SSL3[%d] Cannot gather data; fatal alert already sent", 456 SSL_GETPID(), ss->fd)); 457 PORT_SetError(SSL_ERROR_HANDSHAKE_FAILED); 458 return -1; 459 } 460 461 SSL_TRC(30, ("%d: SSL3[%d]: ssl3_GatherCompleteHandshake", 462 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 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); 469 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 470 471 do { 472 PRBool processingEarlyData; 473 474 ssl_GetSSL3HandshakeLock(ss); 475 476 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 if (ss->ssl3.hs.restartTarget) { 483 ssl_ReleaseSSL3HandshakeLock(ss); 484 PORT_SetError(PR_WOULD_BLOCK_ERROR); 485 return -1; 486 } 487 488 /* If we have a detached record layer, don't ever gather. */ 489 if (ss->recordWriteCallback) { 490 PRBool done = ss->firstHsDone; 491 ssl_ReleaseSSL3HandshakeLock(ss); 492 if (done) { 493 return 1; 494 } 495 PORT_SetError(PR_WOULD_BLOCK_ERROR); 496 return -1; 497 } 498 499 ssl_ReleaseSSL3HandshakeLock(ss); 500 501 /* State for SSLv2 client hello support. */ 502 ssl2Gather ssl2gs = { PR_FALSE, 0 }; 503 ssl2Gather *ssl2gs_ptr = NULL; 504 505 /* If we're a server and waiting for a client hello, accept v2. */ 506 if (ss->sec.isServer && ss->opt.enableV2CompatibleHello && 507 ss->ssl3.hs.ws == wait_client_hello) { 508 ssl2gs_ptr = &ssl2gs; 509 } 510 511 /* bring in the next sslv3 record. */ 512 if (ss->recvdCloseNotify) { 513 /* RFC 5246 Section 7.2.1: 514 * Any data received after a closure alert is ignored. 515 */ 516 return 0; 517 } 518 519 if (!IS_DTLS(ss)) { 520 /* If we're a server waiting for a ClientHello then pass 521 * ssl2gs to support SSLv2 ClientHello messages. */ 522 rv = ssl3_GatherData(ss, &ss->gs, flags, ssl2gs_ptr); 523 } else { 524 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 if (rv == SECFailure && 530 (PORT_GetError() == PR_WOULD_BLOCK_ERROR)) { 531 dtls_CheckTimer(ss); 532 /* Restore the error in case something succeeded */ 533 PORT_SetError(PR_WOULD_BLOCK_ERROR); 534 } 535 } 536 537 if (rv <= 0) { 538 return rv; 539 } 540 541 if (ssl2gs.isV2) { 542 rv = ssl3_HandleV2ClientHello(ss, ss->gs.inbuf.buf, 543 ss->gs.inbuf.len, 544 ssl2gs.padding); 545 if (rv < 0) { 546 return rv; 547 } 548 } 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 cText.hdr = ss->gs.hdr; 558 cText.hdrLen = ss->gs.hdrLen; 559 cText.buf = &ss->gs.inbuf; 560 rv = ssl3_HandleRecord(ss, &cText); 561 } 562 563 #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 sslBuffer_Clear(&ss->gs.inbuf); 569 #endif 570 571 if (rv < 0) { 572 return ss->recvdCloseNotify ? 0 : rv; 573 } 574 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 PORT_Assert(ss->firstHsDone); 580 break; 581 } 582 583 PORT_Assert(keepGoing); 584 ssl_GetSSL3HandshakeLock(ss); 585 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 PORT_Assert(ss->firstHsDone); 593 PORT_Assert(!ss->ssl3.hs.canFalseStart); 594 keepGoing = PR_FALSE; 595 } 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 PORT_Assert(!ss->firstHsDone); 605 606 if (ssl3_WaitingForServerSecondRound(ss)) { 607 keepGoing = PR_FALSE; 608 } else { 609 ss->ssl3.hs.canFalseStart = PR_FALSE; 610 } 611 } else if (processingEarlyData && 612 ss->ssl3.hs.zeroRttState == ssl_0rtt_done && 613 !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 ssl_ReleaseSSL3HandshakeLock(ss); 618 PORT_SetError(PR_WOULD_BLOCK_ERROR); 619 return -1; 620 } 621 ssl_ReleaseSSL3HandshakeLock(ss); 622 } while (keepGoing); 623 624 /* Service the DTLS timer so that the post-handshake timers 625 * fire. */ 626 if (IS_DTLS(ss) && (ss->ssl3.hs.ws == idle_handshake)) { 627 dtls_CheckTimer(ss); 628 } 629 ss->gs.readOffset = 0; 630 ss->gs.writeOffset = ss->gs.buf.len; 631 return 1; 632 } 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 { 647 int rv; 648 649 /* ssl3_GatherCompleteHandshake requires both of these locks. */ 650 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); 651 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 652 653 do { 654 rv = ssl3_GatherCompleteHandshake(ss, flags); 655 } while (rv > 0 && ss->gs.buf.len == 0); 656 657 return rv; 658 } 659 660 static SECStatus 661 ssl_HandleZeroRttRecordData(sslSocket *ss, const PRUint8 *data, unsigned int len) 662 { 663 PORT_Assert(ss->sec.isServer); 664 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) { 665 sslBuffer buf = { CONST_CAST(PRUint8, data), len, len, PR_TRUE }; 666 return tls13_HandleEarlyApplicationData(ss, &buf); 667 } 668 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored && 669 ss->ssl3.hs.zeroRttIgnore != ssl_0rtt_ignore_none) { 670 /* We're ignoring 0-RTT so drop this record quietly. */ 671 return SECSuccess; 672 } 673 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); 674 return SECFailure; 675 } 676 677 /* Ensure that application data in the wrong epoch is blocked. */ 678 static PRBool 679 ssl_IsApplicationDataPermitted(sslSocket *ss, PRUint16 epoch) 680 { 681 /* Epoch 0 is never OK. */ 682 if (epoch == 0) { 683 return PR_FALSE; 684 } 685 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { 686 return ss->firstHsDone; 687 } 688 /* TLS 1.3 application data. */ 689 if (epoch >= TrafficKeyApplicationData) { 690 return ss->firstHsDone; 691 } 692 /* TLS 1.3 early data is server only. Further checks aren't needed 693 * as those are handled in ssl_HandleZeroRttRecordData. */ 694 if (epoch == TrafficKeyEarlyApplicationData) { 695 return ss->sec.isServer; 696 } 697 return PR_FALSE; 698 } 699 700 SECStatus 701 SSLExp_RecordLayerData(PRFileDesc *fd, PRUint16 epoch, 702 SSLContentType contentType, 703 const PRUint8 *data, unsigned int len) 704 { 705 SECStatus rv; 706 sslSocket *ss = ssl_FindSocket(fd); 707 if (!ss) { 708 return SECFailure; 709 } 710 if (IS_DTLS(ss) || data == NULL || len == 0) { 711 PORT_SetError(SEC_ERROR_INVALID_ARGS); 712 return SECFailure; 713 } 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 ssl_Get1stHandshakeLock(ss); 721 rv = ssl_Do1stHandshake(ss); 722 if (rv != SECSuccess && PORT_GetError() != PR_WOULD_BLOCK_ERROR) { 723 goto early_loser; /* Rely on the existing code. */ 724 } 725 726 if (contentType == ssl_ct_application_data && 727 !ssl_IsApplicationDataPermitted(ss, epoch)) { 728 PORT_SetError(SEC_ERROR_INVALID_ARGS); 729 goto early_loser; 730 } 731 732 /* Then we can validate the epoch. */ 733 PRErrorCode epochError; 734 ssl_GetSpecReadLock(ss); 735 if (epoch < ss->ssl3.crSpec->epoch) { 736 epochError = SEC_ERROR_INVALID_ARGS; /* Too c/old. */ 737 } 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 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && 742 ss->opt.suppressEndOfEarlyData && 743 ss->sec.isServer && 744 ss->ssl3.crSpec->epoch == TrafficKeyEarlyApplicationData && 745 epoch == TrafficKeyHandshake) { 746 epochError = 0; 747 } else { 748 epochError = PR_WOULD_BLOCK_ERROR; /* Too warm/new. */ 749 } 750 } else { 751 epochError = 0; /* Just right. */ 752 } 753 ssl_ReleaseSpecReadLock(ss); 754 if (epochError) { 755 PORT_SetError(epochError); 756 goto early_loser; 757 } 758 759 /* If the handshake is still running, we need to run that. */ 760 rv = ssl_Do1stHandshake(ss); 761 if (rv != SECSuccess && PORT_GetError() != PR_WOULD_BLOCK_ERROR) { 762 goto early_loser; 763 } 764 765 /* 0-RTT needs its own special handling here. */ 766 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && 767 epoch == TrafficKeyEarlyApplicationData && 768 contentType == ssl_ct_application_data) { 769 rv = ssl_HandleZeroRttRecordData(ss, data, len); 770 ssl_Release1stHandshakeLock(ss); 771 return rv; 772 } 773 774 /* Finally, save the data... */ 775 ssl_GetRecvBufLock(ss); 776 rv = sslBuffer_Append(&ss->gs.buf, data, len); 777 if (rv != SECSuccess) { 778 goto loser; 779 } 780 781 /* ...and process it. Just saving application data is enough for it to be 782 * available to PR_Read(). */ 783 if (contentType != ssl_ct_application_data) { 784 rv = ssl3_HandleNonApplicationData(ss, contentType, 0, 0, &ss->gs.buf); 785 /* This occasionally blocks, but that's OK here. */ 786 if (rv != SECSuccess && PORT_GetError() != PR_WOULD_BLOCK_ERROR) { 787 goto loser; 788 } 789 } 790 791 ssl_ReleaseRecvBufLock(ss); 792 ssl_Release1stHandshakeLock(ss); 793 return SECSuccess; 794 795 loser: 796 /* Make sure that any data is not used again. */ 797 ss->gs.buf.len = 0; 798 ssl_ReleaseRecvBufLock(ss); 799 early_loser: 800 ssl_Release1stHandshakeLock(ss); 801 return SECFailure; 802 } 803 804 SECStatus 805 SSLExp_GetCurrentEpoch(PRFileDesc *fd, PRUint16 *readEpoch, 806 PRUint16 *writeEpoch) 807 { 808 sslSocket *ss = ssl_FindSocket(fd); 809 if (!ss) { 810 return SECFailure; 811 } 812 813 ssl_GetSpecReadLock(ss); 814 if (readEpoch) { 815 *readEpoch = ss->ssl3.crSpec->epoch; 816 } 817 if (writeEpoch) { 818 *writeEpoch = ss->ssl3.cwSpec->epoch; 819 } 820 ssl_ReleaseSpecReadLock(ss); 821 return SECSuccess; 822 }