/* * Parse the client's renegotiation binding and abort if it's not right */ int ssl_parse_clienthello_renegotiate_ext(SSL *s, PACKET *pkt, int *al) { unsigned int ilen; unsigned char *d; /* Parse the length byte */ if (!PACKET_get_1(pkt, &ilen) || !PACKET_get_bytes(pkt, &d, ilen)) { SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT, SSL_R_RENEGOTIATION_ENCODING_ERR); *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } /* Check that the extension matches */ if (ilen != s->s3->previous_client_finished_len) { SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT, SSL_R_RENEGOTIATION_MISMATCH); *al = SSL_AD_HANDSHAKE_FAILURE; return 0; } if (memcmp(d, s->s3->previous_client_finished, s->s3->previous_client_finished_len)) { SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT, SSL_R_RENEGOTIATION_MISMATCH); *al = SSL_AD_HANDSHAKE_FAILURE; return 0; } #ifdef OPENSSL_RI_DEBUG fprintf(stderr, "%s RI extension received by server\n", ilen ? "Non-empty" : "Empty"); #endif s->s3->send_connection_binding = 1; return 1; }
/* * Process a psk_kex_modes extension received in the ClientHello. |pkt| contains * the raw PACKET data for the extension. Returns 1 on success or 0 on failure. * If a failure occurs then |*al| is set to an appropriate alert value. */ int tls_parse_ctos_psk_kex_modes(SSL *s, PACKET *pkt, unsigned int context, X509 *x, size_t chainidx, int *al) { #ifndef OPENSSL_NO_TLS1_3 PACKET psk_kex_modes; unsigned int mode; if (!PACKET_as_length_prefixed_1(pkt, &psk_kex_modes) || PACKET_remaining(&psk_kex_modes) == 0) { *al = SSL_AD_DECODE_ERROR; return 0; } while (PACKET_get_1(&psk_kex_modes, &mode)) { if (mode == TLSEXT_KEX_MODE_KE_DHE) s->ext.psk_kex_mode |= TLSEXT_KEX_MODE_FLAG_KE_DHE; else if (mode == TLSEXT_KEX_MODE_KE) s->ext.psk_kex_mode |= TLSEXT_KEX_MODE_FLAG_KE; } #endif return 1; }
/*- * The servername extension is treated as follows: * * - Only the hostname type is supported with a maximum length of 255. * - The servername is rejected if too long or if it contains zeros, * in which case an fatal alert is generated. * - The servername field is maintained together with the session cache. * - When a session is resumed, the servername call back invoked in order * to allow the application to position itself to the right context. * - The servername is acknowledged if it is new for a session or when * it is identical to a previously used for the same session. * Applications can control the behaviour. They can at any time * set a 'desirable' servername for a new SSL object. This can be the * case for example with HTTPS when a Host: header field is received and * a renegotiation is requested. In this case, a possible servername * presented in the new client hello is only acknowledged if it matches * the value of the Host: field. * - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION * if they provide for changing an explicit servername context for the * session, i.e. when the session has been established with a servername * extension. * - On session reconnect, the servername extension may be absent. */ int tls_parse_ctos_server_name(SSL *s, PACKET *pkt, unsigned int context, X509 *x, size_t chainidx, int *al) { unsigned int servname_type; PACKET sni, hostname; if (!PACKET_as_length_prefixed_2(pkt, &sni) /* ServerNameList must be at least 1 byte long. */ || PACKET_remaining(&sni) == 0) { *al = SSL_AD_DECODE_ERROR; return 0; } /* * Although the intent was for server_name to be extensible, RFC 4366 * was not clear about it; and so OpenSSL among other implementations, * always and only allows a 'host_name' name types. * RFC 6066 corrected the mistake but adding new name types * is nevertheless no longer feasible, so act as if no other * SNI types can exist, to simplify parsing. * * Also note that the RFC permits only one SNI value per type, * i.e., we can only have a single hostname. */ if (!PACKET_get_1(&sni, &servname_type) || servname_type != TLSEXT_NAMETYPE_host_name || !PACKET_as_length_prefixed_2(&sni, &hostname)) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!s->hit) { if (PACKET_remaining(&hostname) > TLSEXT_MAXLEN_host_name) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } if (PACKET_contains_zero_byte(&hostname)) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } OPENSSL_free(s->session->ext.hostname); s->session->ext.hostname = NULL; if (!PACKET_strndup(&hostname, &s->session->ext.hostname)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->servername_done = 1; } else { /* * TODO(openssl-team): if the SNI doesn't match, we MUST * fall back to a full handshake. */ s->servername_done = s->session->ext.hostname && PACKET_equal(&hostname, s->session->ext.hostname, strlen(s->session->ext.hostname)); } return 1; }
int tls_parse_ctos_use_srtp(SSL *s, PACKET *pkt, unsigned int context, X509 *x, size_t chainidx, int *al) { STACK_OF(SRTP_PROTECTION_PROFILE) *srvr; unsigned int ct, mki_len, id; int i, srtp_pref; PACKET subpkt; /* Ignore this if we have no SRTP profiles */ if (SSL_get_srtp_profiles(s) == NULL) return 1; /* Pull off the length of the cipher suite list and check it is even */ if (!PACKET_get_net_2(pkt, &ct) || (ct & 1) != 0 || !PACKET_get_sub_packet(pkt, &subpkt, ct)) { SSLerr(SSL_F_TLS_PARSE_CTOS_USE_SRTP, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST); *al = SSL_AD_DECODE_ERROR; return 0; } srvr = SSL_get_srtp_profiles(s); s->srtp_profile = NULL; /* Search all profiles for a match initially */ srtp_pref = sk_SRTP_PROTECTION_PROFILE_num(srvr); while (PACKET_remaining(&subpkt)) { if (!PACKET_get_net_2(&subpkt, &id)) { SSLerr(SSL_F_TLS_PARSE_CTOS_USE_SRTP, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST); *al = SSL_AD_DECODE_ERROR; return 0; } /* * Only look for match in profiles of higher preference than * current match. * If no profiles have been have been configured then this * does nothing. */ for (i = 0; i < srtp_pref; i++) { SRTP_PROTECTION_PROFILE *sprof = sk_SRTP_PROTECTION_PROFILE_value(srvr, i); if (sprof->id == id) { s->srtp_profile = sprof; srtp_pref = i; break; } } } /* Now extract the MKI value as a sanity check, but discard it for now */ if (!PACKET_get_1(pkt, &mki_len)) { SSLerr(SSL_F_TLS_PARSE_CTOS_USE_SRTP, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST); *al = SSL_AD_DECODE_ERROR; return 0; } if (!PACKET_forward(pkt, mki_len) || PACKET_remaining(pkt)) { SSLerr(SSL_F_TLS_PARSE_CTOS_USE_SRTP, SSL_R_BAD_SRTP_MKI_VALUE); *al = SSL_AD_DECODE_ERROR; return 0; } return 1; }
int tls_parse_ctos_status_request(SSL *s, PACKET *pkt, unsigned int context, X509 *x, size_t chainidx, int *al) { PACKET responder_id_list, exts; /* Not defined if we get one of these in a client Certificate */ if (x != NULL) return 1; if (!PACKET_get_1(pkt, (unsigned int *)&s->ext.status_type)) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->ext.status_type != TLSEXT_STATUSTYPE_ocsp) { /* * We don't know what to do with any other type so ignore it. */ s->ext.status_type = TLSEXT_STATUSTYPE_nothing; return 1; } if (!PACKET_get_length_prefixed_2 (pkt, &responder_id_list)) { *al = SSL_AD_DECODE_ERROR; return 0; } /* * We remove any OCSP_RESPIDs from a previous handshake * to prevent unbounded memory growth - CVE-2016-6304 */ sk_OCSP_RESPID_pop_free(s->ext.ocsp.ids, OCSP_RESPID_free); if (PACKET_remaining(&responder_id_list) > 0) { s->ext.ocsp.ids = sk_OCSP_RESPID_new_null(); if (s->ext.ocsp.ids == NULL) { *al = SSL_AD_INTERNAL_ERROR; return 0; } } else { s->ext.ocsp.ids = NULL; } while (PACKET_remaining(&responder_id_list) > 0) { OCSP_RESPID *id; PACKET responder_id; const unsigned char *id_data; if (!PACKET_get_length_prefixed_2(&responder_id_list, &responder_id) || PACKET_remaining(&responder_id) == 0) { *al = SSL_AD_DECODE_ERROR; return 0; } id_data = PACKET_data(&responder_id); /* TODO(size_t): Convert d2i_* to size_t */ id = d2i_OCSP_RESPID(NULL, &id_data, (int)PACKET_remaining(&responder_id)); if (id == NULL) { *al = SSL_AD_DECODE_ERROR; return 0; } if (id_data != PACKET_end(&responder_id)) { OCSP_RESPID_free(id); *al = SSL_AD_DECODE_ERROR; return 0; } if (!sk_OCSP_RESPID_push(s->ext.ocsp.ids, id)) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } } /* Read in request_extensions */ if (!PACKET_as_length_prefixed_2(pkt, &exts)) { *al = SSL_AD_DECODE_ERROR; return 0; } if (PACKET_remaining(&exts) > 0) { const unsigned char *ext_data = PACKET_data(&exts); sk_X509_EXTENSION_pop_free(s->ext.ocsp.exts, X509_EXTENSION_free); s->ext.ocsp.exts = d2i_X509_EXTENSIONS(NULL, &ext_data, (int)PACKET_remaining(&exts)); if (s->ext.ocsp.exts == NULL || ext_data != PACKET_end(&exts)) { *al = SSL_AD_DECODE_ERROR; return 0; } } return 1; }
int DTLSv1_listen(SSL *s, BIO_ADDR *client) { int next, n, ret = 0, clearpkt = 0; unsigned char cookie[DTLS1_COOKIE_LENGTH]; unsigned char seq[SEQ_NUM_SIZE]; const unsigned char *data; unsigned char *p, *buf; unsigned long reclen, fragoff, fraglen, msglen; unsigned int rectype, versmajor, msgseq, msgtype, clientvers, cookielen; BIO *rbio, *wbio; BUF_MEM *bufm; BIO_ADDR *tmpclient = NULL; PACKET pkt, msgpkt, msgpayload, session, cookiepkt; /* Ensure there is no state left over from a previous invocation */ if (!SSL_clear(s)) return -1; ERR_clear_error(); rbio = SSL_get_rbio(s); wbio = SSL_get_wbio(s); if (!rbio || !wbio) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_BIO_NOT_SET); return -1; } /* * We only peek at incoming ClientHello's until we're sure we are going to * to respond with a HelloVerifyRequest. If its a ClientHello with a valid * cookie then we leave it in the BIO for accept to handle. */ BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 1, NULL); /* * Note: This check deliberately excludes DTLS1_BAD_VER because that version * requires the MAC to be calculated *including* the first ClientHello * (without the cookie). Since DTLSv1_listen is stateless that cannot be * supported. DTLS1_BAD_VER must use cookies in a stateful manner (e.g. via * SSL_accept) */ if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNSUPPORTED_SSL_VERSION); return -1; } if (s->init_buf == NULL) { if ((bufm = BUF_MEM_new()) == NULL) { SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE); return -1; } if (!BUF_MEM_grow(bufm, SSL3_RT_MAX_PLAIN_LENGTH)) { BUF_MEM_free(bufm); SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE); return -1; } s->init_buf = bufm; } buf = (unsigned char *)s->init_buf->data; do { /* Get a packet */ clear_sys_error(); /* * Technically a ClientHello could be SSL3_RT_MAX_PLAIN_LENGTH * + DTLS1_RT_HEADER_LENGTH bytes long. Normally init_buf does not store * the record header as well, but we do here. We've set up init_buf to * be the standard size for simplicity. In practice we shouldn't ever * receive a ClientHello as long as this. If we do it will get dropped * in the record length check below. */ n = BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH); if (n <= 0) { if (BIO_should_retry(rbio)) { /* Non-blocking IO */ goto end; } return -1; } /* If we hit any problems we need to clear this packet from the BIO */ clearpkt = 1; if (!PACKET_buf_init(&pkt, buf, n)) { SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_INTERNAL_ERROR); return -1; } /* * Parse the received record. If there are any problems with it we just * dump it - with no alert. RFC6347 says this "Unlike TLS, DTLS is * resilient in the face of invalid records (e.g., invalid formatting, * length, MAC, etc.). In general, invalid records SHOULD be silently * discarded, thus preserving the association; however, an error MAY be * logged for diagnostic purposes." */ /* this packet contained a partial record, dump it */ if (n < DTLS1_RT_HEADER_LENGTH) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_RECORD_TOO_SMALL); goto end; } if (s->msg_callback) s->msg_callback(0, 0, SSL3_RT_HEADER, buf, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg); /* Get the record header */ if (!PACKET_get_1(&pkt, &rectype) || !PACKET_get_1(&pkt, &versmajor)) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH); goto end; } if (rectype != SSL3_RT_HANDSHAKE) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE); goto end; } /* * Check record version number. We only check that the major version is * the same. */ if (versmajor != DTLS1_VERSION_MAJOR) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_BAD_PROTOCOL_VERSION_NUMBER); goto end; } if (!PACKET_forward(&pkt, 1) /* Save the sequence number: 64 bits, with top 2 bytes = epoch */ || !PACKET_copy_bytes(&pkt, seq, SEQ_NUM_SIZE) || !PACKET_get_length_prefixed_2(&pkt, &msgpkt)) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH); goto end; } /* * We allow data remaining at the end of the packet because there could * be a second record (but we ignore it) */ /* This is an initial ClientHello so the epoch has to be 0 */ if (seq[0] != 0 || seq[1] != 0) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE); goto end; } /* Get a pointer to the raw message for the later callback */ data = PACKET_data(&msgpkt); /* Finished processing the record header, now process the message */ if (!PACKET_get_1(&msgpkt, &msgtype) || !PACKET_get_net_3(&msgpkt, &msglen) || !PACKET_get_net_2(&msgpkt, &msgseq) || !PACKET_get_net_3(&msgpkt, &fragoff) || !PACKET_get_net_3(&msgpkt, &fraglen) || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen) || PACKET_remaining(&msgpkt) != 0) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH); goto end; } if (msgtype != SSL3_MT_CLIENT_HELLO) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_UNEXPECTED_MESSAGE); goto end; } /* Message sequence number can only be 0 or 1 */ if (msgseq > 2) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_INVALID_SEQUENCE_NUMBER); goto end; } /* * We don't support fragment reassembly for ClientHellos whilst * listening because that would require server side state (which is * against the whole point of the ClientHello/HelloVerifyRequest * mechanism). Instead we only look at the first ClientHello fragment * and require that the cookie must be contained within it. */ if (fragoff != 0 || fraglen > msglen) { /* Non initial ClientHello fragment (or bad fragment) */ SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_FRAGMENTED_CLIENT_HELLO); goto end; } if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, data, fraglen + DTLS1_HM_HEADER_LENGTH, s, s->msg_callback_arg); if (!PACKET_get_net_2(&msgpayload, &clientvers)) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH); goto end; } /* * Verify client version is supported */ if (DTLS_VERSION_LT(clientvers, (unsigned int)s->method->version) && s->method->version != DTLS_ANY_VERSION) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_WRONG_VERSION_NUMBER); goto end; } if (!PACKET_forward(&msgpayload, SSL3_RANDOM_SIZE) || !PACKET_get_length_prefixed_1(&msgpayload, &session) || !PACKET_get_length_prefixed_1(&msgpayload, &cookiepkt)) { /* * Could be malformed or the cookie does not fit within the initial * ClientHello fragment. Either way we can't handle it. */ SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_LENGTH_MISMATCH); goto end; } /* * Check if we have a cookie or not. If not we need to send a * HelloVerifyRequest. */ if (PACKET_remaining(&cookiepkt) == 0) { next = LISTEN_SEND_VERIFY_REQUEST; } else { /* * We have a cookie, so lets check it. */ if (s->ctx->app_verify_cookie_cb == NULL) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_NO_VERIFY_COOKIE_CALLBACK); /* This is fatal */ return -1; } if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookiepkt), PACKET_remaining(&cookiepkt)) == 0) { /* * We treat invalid cookies in the same was as no cookie as * per RFC6347 */ next = LISTEN_SEND_VERIFY_REQUEST; } else { /* Cookie verification succeeded */ next = LISTEN_SUCCESS; } } if (next == LISTEN_SEND_VERIFY_REQUEST) { /* * There was no cookie in the ClientHello so we need to send a * HelloVerifyRequest. If this fails we do not worry about trying * to resend, we just drop it. */ /* * Dump the read packet, we don't need it any more. Ignore return * value */ BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 0, NULL); BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH); BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_PEEK_MODE, 1, NULL); /* Generate the cookie */ if (s->ctx->app_gen_cookie_cb == NULL || s->ctx->app_gen_cookie_cb(s, cookie, &cookielen) == 0 || cookielen > 255) { SSLerr(SSL_F_DTLSV1_LISTEN, SSL_R_COOKIE_GEN_CALLBACK_FAILURE); /* This is fatal */ return -1; } p = &buf[DTLS1_RT_HEADER_LENGTH]; msglen = dtls_raw_hello_verify_request(p + DTLS1_HM_HEADER_LENGTH, cookie, cookielen); *p++ = DTLS1_MT_HELLO_VERIFY_REQUEST; /* Message length */ l2n3(msglen, p); /* Message sequence number is always 0 for a HelloVerifyRequest */ s2n(0, p); /* * We never fragment a HelloVerifyRequest, so fragment offset is 0 * and fragment length is message length */ l2n3(0, p); l2n3(msglen, p); /* Set reclen equal to length of whole handshake message */ reclen = msglen + DTLS1_HM_HEADER_LENGTH; /* Add the record header */ p = buf; *(p++) = SSL3_RT_HANDSHAKE; /* * Special case: for hello verify request, client version 1.0 and we * haven't decided which version to use yet send back using version * 1.0 header: otherwise some clients will ignore it. */ if (s->method->version == DTLS_ANY_VERSION) { *(p++) = DTLS1_VERSION >> 8; *(p++) = DTLS1_VERSION & 0xff; } else { *(p++) = s->version >> 8; *(p++) = s->version & 0xff; } /* * Record sequence number is always the same as in the received * ClientHello */ memcpy(p, seq, SEQ_NUM_SIZE); p += SEQ_NUM_SIZE; /* Length */ s2n(reclen, p); /* * Set reclen equal to length of whole record including record * header */ reclen += DTLS1_RT_HEADER_LENGTH; if (s->msg_callback) s->msg_callback(1, 0, SSL3_RT_HEADER, buf, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg); if ((tmpclient = BIO_ADDR_new()) == NULL) { SSLerr(SSL_F_DTLSV1_LISTEN, ERR_R_MALLOC_FAILURE); goto end; } /* * This is unnecessary if rbio and wbio are one and the same - but * maybe they're not. We ignore errors here - some BIOs do not * support this. */ if (BIO_dgram_get_peer(rbio, tmpclient) > 0) { (void)BIO_dgram_set_peer(wbio, tmpclient); } BIO_ADDR_free(tmpclient); tmpclient = NULL; if (BIO_write(wbio, buf, reclen) < (int)reclen) { if (BIO_should_retry(wbio)) { /* * Non-blocking IO...but we're stateless, so we're just * going to drop this packet. */ goto end; } return -1; } if (BIO_flush(wbio) <= 0) { if (BIO_should_retry(wbio)) { /* * Non-blocking IO...but we're stateless, so we're just * going to drop this packet. */ goto end; } return -1; } }
/*- * Return up to 'len' payload bytes received in 'type' records. * 'type' is one of the following: * * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us) * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us) * - 0 (during a shutdown, no data has to be returned) * * If we don't have stored data to work from, read a SSL/TLS record first * (possibly multiple records if we still don't have anything to return). * * This function must handle any surprises the peer may have for us, such as * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec * messages are treated as if they were handshake messages *if* the |recd_type| * argument is non NULL. * Also if record payloads contain fragments too small to process, we store * them until there is enough for the respective protocol (the record protocol * may use arbitrary fragmentation and even interleaving): * Change cipher spec protocol * just 1 byte needed, no need for keeping anything stored * Alert protocol * 2 bytes needed (AlertLevel, AlertDescription) * Handshake protocol * 4 bytes needed (HandshakeType, uint24 length) -- we just have * to detect unexpected Client Hello and Hello Request messages * here, anything else is handled by higher layers * Application data protocol * none of our business */ int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf, size_t len, int peek, size_t *readbytes) { int i, j, iret; size_t n; SSL3_RECORD *rr; void (*cb) (const SSL *ssl, int type2, int val) = NULL; if (!SSL3_BUFFER_is_initialised(&s->rlayer.rbuf)) { /* Not initialized yet */ if (!ssl3_setup_buffers(s)) { /* SSLfatal() already called */ return -1; } } if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) { /* type == SSL3_RT_APPLICATION_DATA */ i = s->handshake_func(s); /* SSLfatal() already called if appropriate */ if (i < 0) return i; if (i == 0) return -1; } start: s->rwstate = SSL_NOTHING; /*- * s->s3.rrec.type - is the type of record * s->s3.rrec.data, - data * s->s3.rrec.off, - offset into 'data' for next read * s->s3.rrec.length, - number of bytes. */ rr = s->rlayer.rrec; /* * We are not handshaking and have no data yet, so process data buffered * during the last handshake in advance, if any. */ if (SSL_is_init_finished(s) && SSL3_RECORD_get_length(rr) == 0) { pitem *item; item = pqueue_pop(s->rlayer.d->buffered_app_data.q); if (item) { #ifndef OPENSSL_NO_SCTP /* Restore bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s))) { DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif dtls1_copy_record(s, item); OPENSSL_free(item->data); pitem_free(item); } } /* Check for timeout */ if (dtls1_handle_timeout(s) > 0) { goto start; } else if (ossl_statem_in_error(s)) { /* dtls1_handle_timeout() has failed with a fatal error */ return -1; } /* get new packet if necessary */ if ((SSL3_RECORD_get_length(rr) == 0) || (s->rlayer.rstate == SSL_ST_READ_BODY)) { RECORD_LAYER_set_numrpipes(&s->rlayer, 0); iret = dtls1_get_record(s); if (iret <= 0) { iret = dtls1_read_failed(s, iret); /* * Anything other than a timeout is an error. SSLfatal() already * called if appropriate. */ if (iret <= 0) return iret; else goto start; } RECORD_LAYER_set_numrpipes(&s->rlayer, 1); } /* * Reset the count of consecutive warning alerts if we've got a non-empty * record that isn't an alert. */ if (SSL3_RECORD_get_type(rr) != SSL3_RT_ALERT && SSL3_RECORD_get_length(rr) != 0) s->rlayer.alert_count = 0; /* we now have a packet which can be read and processed */ if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec, * reset by ssl3_get_finished */ && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) { /* * We now have application data between CCS and Finished. Most likely * the packets were reordered on their way, so buffer the application * data for later processing rather than dropping the connection. */ if (dtls1_buffer_record(s, &(s->rlayer.d->buffered_app_data), SSL3_RECORD_get_seq_num(rr)) < 0) { /* SSLfatal() already called */ return -1; } SSL3_RECORD_set_length(rr, 0); SSL3_RECORD_set_read(rr); goto start; } /* * If the other end has shut down, throw anything we read away (even in * 'peek' mode) */ if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { SSL3_RECORD_set_length(rr, 0); SSL3_RECORD_set_read(rr); s->rwstate = SSL_NOTHING; return 0; } if (type == SSL3_RECORD_get_type(rr) || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) { /* * SSL3_RT_APPLICATION_DATA or * SSL3_RT_HANDSHAKE or * SSL3_RT_CHANGE_CIPHER_SPEC */ /* * make sure that we are not getting application data when we are * doing a handshake for the first time */ if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && (s->enc_read_ctx == NULL)) { SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE); return -1; } if (recvd_type != NULL) *recvd_type = SSL3_RECORD_get_type(rr); if (len == 0) { /* * Mark a zero length record as read. This ensures multiple calls to * SSL_read() with a zero length buffer will eventually cause * SSL_pending() to report data as being available. */ if (SSL3_RECORD_get_length(rr) == 0) SSL3_RECORD_set_read(rr); return 0; } if (len > SSL3_RECORD_get_length(rr)) n = SSL3_RECORD_get_length(rr); else n = len; memcpy(buf, &(SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)]), n); if (peek) { if (SSL3_RECORD_get_length(rr) == 0) SSL3_RECORD_set_read(rr); } else { SSL3_RECORD_sub_length(rr, n); SSL3_RECORD_add_off(rr, n); if (SSL3_RECORD_get_length(rr) == 0) { s->rlayer.rstate = SSL_ST_READ_HEADER; SSL3_RECORD_set_off(rr, 0); SSL3_RECORD_set_read(rr); } } #ifndef OPENSSL_NO_SCTP /* * We might had to delay a close_notify alert because of reordered * app data. If there was an alert and there is no message to read * anymore, finally set shutdown. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && s->d1->shutdown_received && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return 0; } #endif *readbytes = n; return 1; } /* * If we get here, then type != rr->type; if we have a handshake message, * then it was unexpected (Hello Request or Client Hello). */ if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) { unsigned int alert_level, alert_descr; unsigned char *alert_bytes = SSL3_RECORD_get_data(rr) + SSL3_RECORD_get_off(rr); PACKET alert; if (!PACKET_buf_init(&alert, alert_bytes, SSL3_RECORD_get_length(rr)) || !PACKET_get_1(&alert, &alert_level) || !PACKET_get_1(&alert, &alert_descr) || PACKET_remaining(&alert) != 0) { SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_DTLS1_READ_BYTES, SSL_R_INVALID_ALERT); return -1; } if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; if (cb != NULL) { j = (alert_level << 8) | alert_descr; cb(s, SSL_CB_READ_ALERT, j); } if (alert_level == SSL3_AL_WARNING) { s->s3.warn_alert = alert_descr; SSL3_RECORD_set_read(rr); s->rlayer.alert_count++; if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) { SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_DTLS1_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS); return -1; } if (alert_descr == SSL_AD_CLOSE_NOTIFY) { #ifndef OPENSSL_NO_SCTP /* * With SCTP and streams the socket may deliver app data * after a close_notify alert. We have to check this first so * that nothing gets discarded. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->d1->shutdown_received = 1; s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return -1; } #endif s->shutdown |= SSL_RECEIVED_SHUTDOWN; return 0; } } else if (alert_level == SSL3_AL_FATAL) { char tmp[16]; s->rwstate = SSL_NOTHING; s->s3.fatal_alert = alert_descr; SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr); ERR_add_error_data(2, "SSL alert number ", tmp); s->shutdown |= SSL_RECEIVED_SHUTDOWN; SSL3_RECORD_set_read(rr); SSL_CTX_remove_session(s->session_ctx, s->session); return 0; } else { SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE); return -1; } goto start; } if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a * shutdown */ s->rwstate = SSL_NOTHING; SSL3_RECORD_set_length(rr, 0); SSL3_RECORD_set_read(rr); return 0; } if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) { /* * We can't process a CCS now, because previous handshake messages * are still missing, so just drop it. */ SSL3_RECORD_set_length(rr, 0); SSL3_RECORD_set_read(rr); goto start; } /* * Unexpected handshake message (Client Hello, or protocol violation) */ if ((SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) && !ossl_statem_get_in_handshake(s)) { struct hm_header_st msg_hdr; /* * This may just be a stale retransmit. Also sanity check that we have * at least enough record bytes for a message header */ if (SSL3_RECORD_get_epoch(rr) != s->rlayer.d->r_epoch || SSL3_RECORD_get_length(rr) < DTLS1_HM_HEADER_LENGTH) { SSL3_RECORD_set_length(rr, 0); SSL3_RECORD_set_read(rr); goto start; } dtls1_get_message_header(rr->data, &msg_hdr); /* * If we are server, we may have a repeated FINISHED of the client * here, then retransmit our CCS and FINISHED. */ if (msg_hdr.type == SSL3_MT_FINISHED) { if (dtls1_check_timeout_num(s) < 0) { /* SSLfatal) already called */ return -1; } if (dtls1_retransmit_buffered_messages(s) <= 0) { /* Fail if we encountered a fatal error */ if (ossl_statem_in_error(s)) return -1; } SSL3_RECORD_set_length(rr, 0); SSL3_RECORD_set_read(rr); if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) { /* no read-ahead left? */ BIO *bio; s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return -1; } } goto start; } /* * To get here we must be trying to read app data but found handshake * data. But if we're trying to read app data, and we're not in init * (which is tested for at the top of this function) then init must be * finished */ if (!ossl_assert(SSL_is_init_finished(s))) { SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } /* We found handshake data, so we're going back into init */ ossl_statem_set_in_init(s, 1); i = s->handshake_func(s); /* SSLfatal() called if appropriate */ if (i < 0) return i; if (i == 0) return -1; if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, but we * trigger an SSL handshake, we return -1 with the retry * option set. Otherwise renegotiation may cause nasty * problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return -1; } } goto start; } switch (SSL3_RECORD_get_type(rr)) { default: SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); return -1; case SSL3_RT_CHANGE_CIPHER_SPEC: case SSL3_RT_ALERT: case SSL3_RT_HANDSHAKE: /* * we already handled all of these, with the possible exception of * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but * that should not happen when type != rr->type */ SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; case SSL3_RT_APPLICATION_DATA: /* * At this point, we were expecting handshake data, but have * application data. If the library was running inside ssl3_read() * (i.e. in_read_app_data is set) and it makes sense to read * application data at this point (session renegotiation not yet * started), we will indulge it. */ if (s->s3.in_read_app_data && (s->s3.total_renegotiations != 0) && ossl_statem_app_data_allowed(s)) { s->s3.in_read_app_data = 2; return -1; } else { SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); return -1; } } /* not reached */ }
static int watchccs_write(BIO *bio, const char *in, int inl) { int ret = 0; BIO *next = BIO_next(bio); PACKET pkt, msg, msgbody, sessionid; unsigned int rectype, recvers, msgtype, expectedrecvers; if (inl <= 0) return 0; if (next == NULL) return 0; BIO_clear_retry_flags(bio); if (!PACKET_buf_init(&pkt, (const unsigned char *)in, inl)) return 0; /* We assume that we always write complete records each time */ while (PACKET_remaining(&pkt)) { if (!PACKET_get_1(&pkt, &rectype) || !PACKET_get_net_2(&pkt, &recvers) || !PACKET_get_length_prefixed_2(&pkt, &msg)) return 0; expectedrecvers = TLS1_2_VERSION; if (rectype == SSL3_RT_HANDSHAKE) { if (!PACKET_get_1(&msg, &msgtype) || !PACKET_get_length_prefixed_3(&msg, &msgbody)) return 0; if (msgtype == SSL3_MT_CLIENT_HELLO) { chseen++; /* * Skip legacy_version (2 bytes) and Random (32 bytes) to read * session_id. */ if (!PACKET_forward(&msgbody, 34) || !PACKET_get_length_prefixed_1(&msgbody, &sessionid)) return 0; if (chseen == 1) { expectedrecvers = TLS1_VERSION; /* Save the session id for later */ chsessidlen = PACKET_remaining(&sessionid); if (!PACKET_copy_bytes(&sessionid, chsessid, chsessidlen)) return 0; } else { /* * Check the session id for the second ClientHello is the * same as the first one. */ if (PACKET_remaining(&sessionid) != chsessidlen || (chsessidlen > 0 && memcmp(chsessid, PACKET_data(&sessionid), chsessidlen) != 0)) badsessid = 1; } } else if (msgtype == SSL3_MT_SERVER_HELLO) { shseen++; /* * Skip legacy_version (2 bytes) and Random (32 bytes) to read * session_id. */ if (!PACKET_forward(&msgbody, 34) || !PACKET_get_length_prefixed_1(&msgbody, &sessionid)) return 0; /* * Check the session id is the same as the one in the * ClientHello */ if (PACKET_remaining(&sessionid) != chsessidlen || (chsessidlen > 0 && memcmp(chsessid, PACKET_data(&sessionid), chsessidlen) != 0)) badsessid = 1; } } else if (rectype == SSL3_RT_CHANGE_CIPHER_SPEC) { if (bio == s_to_c_fbio) { /* * Server writing. We shouldn't have written any app data * yet, and we should have seen both the ClientHello and the * ServerHello */ if (!sappdataseen && chseen == 1 && shseen == 1 && !sccsseen) sccsseen = 1; else badccs = 1; } else if (!cappdataseen) { /* * Client writing. We shouldn't have written any app data * yet, and we should have seen the ClientHello */ if (shseen == 1 && !ccsaftersh) ccsaftersh = 1; else if (shseen == 0 && !ccsbeforesh) ccsbeforesh = 1; else badccs = 1; } else { badccs = 1; } } else if(rectype == SSL3_RT_APPLICATION_DATA) { if (bio == s_to_c_fbio) sappdataseen = 1; else cappdataseen = 1; } if (recvers != expectedrecvers) badvers = 1; } ret = BIO_write(next, in, inl); if (ret <= 0 && BIO_should_write(next)) BIO_set_retry_write(bio); return ret; }