diff options
author | Jung-uk Kim <jkim@FreeBSD.org> | 2016-09-22 13:04:03 +0000 |
---|---|---|
committer | Jung-uk Kim <jkim@FreeBSD.org> | 2016-09-22 13:04:03 +0000 |
commit | e1b483878d9824c63d376895da633b0b96fbbaed (patch) | |
tree | 0846e185ed4cc1159a684e408e772c86ae0fc1a7 /ssl | |
parent | 57f1256b1a087adbdf8e5c080dd9ed7975de939a (diff) | |
download | src-e1b483878d9824c63d376895da633b0b96fbbaed.tar.gz src-e1b483878d9824c63d376895da633b0b96fbbaed.zip |
Notes
Diffstat (limited to 'ssl')
-rw-r--r-- | ssl/Makefile | 2 | ||||
-rw-r--r-- | ssl/bad_dtls_test.c | 923 | ||||
-rw-r--r-- | ssl/d1_both.c | 47 | ||||
-rw-r--r-- | ssl/d1_clnt.c | 1 | ||||
-rw-r--r-- | ssl/d1_lib.c | 37 | ||||
-rw-r--r-- | ssl/d1_pkt.c | 167 | ||||
-rw-r--r-- | ssl/d1_srvr.c | 3 | ||||
-rw-r--r-- | ssl/dtlstest.c | 147 | ||||
-rw-r--r-- | ssl/s23_clnt.c | 8 | ||||
-rw-r--r-- | ssl/s2_clnt.c | 4 | ||||
-rw-r--r-- | ssl/s2_srvr.c | 12 | ||||
-rw-r--r-- | ssl/s3_both.c | 41 | ||||
-rw-r--r-- | ssl/s3_clnt.c | 34 | ||||
-rw-r--r-- | ssl/s3_enc.c | 12 | ||||
-rw-r--r-- | ssl/s3_lib.c | 39 | ||||
-rw-r--r-- | ssl/s3_pkt.c | 19 | ||||
-rw-r--r-- | ssl/s3_srvr.c | 68 | ||||
-rw-r--r-- | ssl/ssl.h | 10 | ||||
-rw-r--r-- | ssl/ssl_asn1.c | 3 | ||||
-rw-r--r-- | ssl/ssl_ciph.c | 21 | ||||
-rw-r--r-- | ssl/ssl_err.c | 4 | ||||
-rw-r--r-- | ssl/ssl_lib.c | 8 | ||||
-rw-r--r-- | ssl/ssl_locl.h | 13 | ||||
-rw-r--r-- | ssl/ssl_rsa.c | 9 | ||||
-rw-r--r-- | ssl/ssl_sess.c | 10 | ||||
-rw-r--r-- | ssl/ssltest.c | 3 | ||||
-rw-r--r-- | ssl/sslv2conftest.c | 2 | ||||
-rw-r--r-- | ssl/t1_enc.c | 1 | ||||
-rw-r--r-- | ssl/t1_lib.c | 106 |
29 files changed, 1522 insertions, 232 deletions
diff --git a/ssl/Makefile b/ssl/Makefile index b6dee5b5ea52..dd1296225006 100644 --- a/ssl/Makefile +++ b/ssl/Makefile @@ -15,7 +15,7 @@ KRB5_INCLUDES= CFLAGS= $(INCLUDES) $(CFLAG) GENERAL=Makefile README ssl-lib.com install.com -TEST=ssltest.c heartbeat_test.c clienthellotest.c sslv2conftest.c +TEST=ssltest.c heartbeat_test.c clienthellotest.c sslv2conftest.c dtlstest.c bad_dtls_test.c APPS= LIB=$(TOP)/libssl.a diff --git a/ssl/bad_dtls_test.c b/ssl/bad_dtls_test.c new file mode 100644 index 000000000000..d42817fc329e --- /dev/null +++ b/ssl/bad_dtls_test.c @@ -0,0 +1,923 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * Unit test for Cisco DTLS1_BAD_VER session resume, as used by + * AnyConnect VPN protocol. + * + * This is designed to exercise the code paths in + * http://git.infradead.org/users/dwmw2/openconnect.git/blob/HEAD:/dtls.c + * which have frequently been affected by regressions in DTLS1_BAD_VER + * support. + * + * Note that unlike other SSL tests, we don't test against our own SSL + * server method. Firstly because we don't have one; we *only* support + * DTLS1_BAD_VER as a client. And secondly because even if that were + * fixed up it's the wrong thing to test against — because if changes + * are made in generic DTLS code which don't take DTLS1_BAD_VER into + * account, there's plenty of scope for making those changes such that + * they break *both* the client and the server in the same way. + * + * So we handle the server side manually. In a session resume there isn't + * much to be done anyway. + */ +#include <string.h> + +/* On Windows this will include <winsock2.h> and thus it needs to be + * included *before* anything that includes <windows.h>. Ick. */ +#include "e_os.h" /* for 'inline' */ + +#include <openssl/bio.h> +#include <openssl/crypto.h> +#include <openssl/evp.h> +#include <openssl/ssl.h> +#include <openssl/err.h> +#include <openssl/rand.h> + +/* PACKET functions lifted from OpenSSL 1.1's ssl/packet_locl.h */ +typedef struct { + /* Pointer to where we are currently reading from */ + const unsigned char *curr; + /* Number of bytes remaining */ + size_t remaining; +} PACKET; + +/* Internal unchecked shorthand; don't use outside this file. */ +static inline void packet_forward(PACKET *pkt, size_t len) +{ + pkt->curr += len; + pkt->remaining -= len; +} + +/* + * Returns the number of bytes remaining to be read in the PACKET + */ +static inline size_t PACKET_remaining(const PACKET *pkt) +{ + return pkt->remaining; +} + +/* + * Initialise a PACKET with |len| bytes held in |buf|. This does not make a + * copy of the data so |buf| must be present for the whole time that the PACKET + * is being used. + */ +static inline int PACKET_buf_init(PACKET *pkt, + const unsigned char *buf, + size_t len) +{ + /* Sanity check for negative values. */ + if (len > (size_t)65536) + return 0; + + pkt->curr = buf; + pkt->remaining = len; + return 1; +} + +/* + * Returns 1 if the packet has length |num| and its contents equal the |num| + * bytes read from |ptr|. Returns 0 otherwise (lengths or contents not equal). + * If lengths are equal, performs the comparison in constant time. + */ +static inline int PACKET_equal(const PACKET *pkt, const void *ptr, + size_t num) +{ + if (PACKET_remaining(pkt) != num) + return 0; + return CRYPTO_memcmp(pkt->curr, ptr, num) == 0; +} + +/* + * Peek ahead at 2 bytes in network order from |pkt| and store the value in + * |*data| + */ +static inline int PACKET_peek_net_2(const PACKET *pkt, + unsigned int *data) +{ + if (PACKET_remaining(pkt) < 2) + return 0; + + *data = ((unsigned int)(*pkt->curr)) << 8; + *data |= *(pkt->curr + 1); + + return 1; +} + +/* Equivalent of n2s */ +/* Get 2 bytes in network order from |pkt| and store the value in |*data| */ +static inline int PACKET_get_net_2(PACKET *pkt, + unsigned int *data) +{ + if (!PACKET_peek_net_2(pkt, data)) + return 0; + + packet_forward(pkt, 2); + + return 1; +} + +/* Peek ahead at 1 byte from |pkt| and store the value in |*data| */ +static inline int PACKET_peek_1(const PACKET *pkt, + unsigned int *data) +{ + if (!PACKET_remaining(pkt)) + return 0; + + *data = *pkt->curr; + + return 1; +} + +/* Get 1 byte from |pkt| and store the value in |*data| */ +static inline int PACKET_get_1(PACKET *pkt, unsigned int *data) +{ + if (!PACKET_peek_1(pkt, data)) + return 0; + + packet_forward(pkt, 1); + + return 1; +} + +/* + * Peek ahead at |len| bytes from the |pkt| and store a pointer to them in + * |*data|. This just points at the underlying buffer that |pkt| is using. The + * caller should not free this data directly (it will be freed when the + * underlying buffer gets freed + */ +static inline int PACKET_peek_bytes(const PACKET *pkt, + const unsigned char **data, + size_t len) +{ + if (PACKET_remaining(pkt) < len) + return 0; + + *data = pkt->curr; + + return 1; +} + +/* + * Read |len| bytes from the |pkt| and store a pointer to them in |*data|. This + * just points at the underlying buffer that |pkt| is using. The caller should + * not free this data directly (it will be freed when the underlying buffer gets + * freed + */ +static inline int PACKET_get_bytes(PACKET *pkt, + const unsigned char **data, + size_t len) +{ + if (!PACKET_peek_bytes(pkt, data, len)) + return 0; + + packet_forward(pkt, len); + + return 1; +} + +/* Peek ahead at |len| bytes from |pkt| and copy them to |data| */ +static inline int PACKET_peek_copy_bytes(const PACKET *pkt, + unsigned char *data, + size_t len) +{ + if (PACKET_remaining(pkt) < len) + return 0; + + memcpy(data, pkt->curr, len); + + return 1; +} + +/* + * Read |len| bytes from |pkt| and copy them to |data|. + * The caller is responsible for ensuring that |data| can hold |len| bytes. + */ +static inline int PACKET_copy_bytes(PACKET *pkt, + unsigned char *data, + size_t len) +{ + if (!PACKET_peek_copy_bytes(pkt, data, len)) + return 0; + + packet_forward(pkt, len); + + return 1; +} + + +/* Move the current reading position forward |len| bytes */ +static inline int PACKET_forward(PACKET *pkt, size_t len) +{ + if (PACKET_remaining(pkt) < len) + return 0; + + packet_forward(pkt, len); + + return 1; +} + +/* + * Reads a variable-length vector prefixed with a one-byte length, and stores + * the contents in |subpkt|. |pkt| can equal |subpkt|. + * Data is not copied: the |subpkt| packet will share its underlying buffer with + * the original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|. + * Upon failure, the original |pkt| and |subpkt| are not modified. + */ +static inline int PACKET_get_length_prefixed_1(PACKET *pkt, + PACKET *subpkt) +{ + unsigned int length; + const unsigned char *data; + PACKET tmp = *pkt; + if (!PACKET_get_1(&tmp, &length) || + !PACKET_get_bytes(&tmp, &data, (size_t)length)) { + return 0; + } + + *pkt = tmp; + subpkt->curr = data; + subpkt->remaining = length; + + return 1; +} + +#define OSSL_NELEM(x) (sizeof(x)/sizeof(x[0])) + +/* For DTLS1_BAD_VER packets the MAC doesn't include the handshake header */ +#define MAC_OFFSET (DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH) + +static unsigned char client_random[SSL3_RANDOM_SIZE]; +static unsigned char server_random[SSL3_RANDOM_SIZE]; + +/* These are all generated locally, sized purely according to our own whim */ +static unsigned char session_id[32]; +static unsigned char master_secret[48]; +static unsigned char cookie[20]; + +/* We've hard-coded the cipher suite; we know it's 104 bytes */ +static unsigned char key_block[104]; +#define mac_key (key_block + 20) +#define dec_key (key_block + 40) +#define enc_key (key_block + 56) + +static EVP_MD_CTX handshake_md5; +static EVP_MD_CTX handshake_sha1; + +/* PRF lifted from ssl/t1_enc.c since we can't easily use it directly */ +static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec, + int sec_len, + const void *seed1, int seed1_len, + const void *seed2, int seed2_len, + const void *seed3, int seed3_len, + unsigned char *out, int olen) +{ + int chunk; + size_t j; + EVP_MD_CTX ctx, ctx_tmp, ctx_init; + EVP_PKEY *prf_mac_key; + unsigned char A1[EVP_MAX_MD_SIZE]; + size_t A1_len; + int ret = 0; + + chunk = EVP_MD_size(md); + OPENSSL_assert(chunk >= 0); + + EVP_MD_CTX_init(&ctx); + EVP_MD_CTX_init(&ctx_tmp); + EVP_MD_CTX_init(&ctx_init); + EVP_MD_CTX_set_flags(&ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); + prf_mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len); + if (!prf_mac_key) + goto err; + if (!EVP_DigestSignInit(&ctx_init, NULL, md, NULL, prf_mac_key)) + goto err; + if (!EVP_MD_CTX_copy_ex(&ctx, &ctx_init)) + goto err; + if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len)) + goto err; + if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len)) + goto err; + if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len)) + goto err; + if (!EVP_DigestSignFinal(&ctx, A1, &A1_len)) + goto err; + + for (;;) { + /* Reinit mac contexts */ + if (!EVP_MD_CTX_copy_ex(&ctx, &ctx_init)) + goto err; + if (!EVP_DigestSignUpdate(&ctx, A1, A1_len)) + goto err; + if (olen > chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp, &ctx)) + goto err; + if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len)) + goto err; + if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len)) + goto err; + if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len)) + goto err; + + if (olen > chunk) { + if (!EVP_DigestSignFinal(&ctx, out, &j)) + goto err; + out += j; + olen -= j; + /* calc the next A1 value */ + if (!EVP_DigestSignFinal(&ctx_tmp, A1, &A1_len)) + goto err; + } else { /* last one */ + + if (!EVP_DigestSignFinal(&ctx, A1, &A1_len)) + goto err; + memcpy(out, A1, olen); + break; + } + } + ret = 1; + err: + EVP_PKEY_free(prf_mac_key); + EVP_MD_CTX_cleanup(&ctx); + EVP_MD_CTX_cleanup(&ctx_tmp); + EVP_MD_CTX_cleanup(&ctx_init); + OPENSSL_cleanse(A1, sizeof(A1)); + return ret; +} + +/* seed1 through seed5 are virtually concatenated */ +static int do_PRF(const void *seed1, int seed1_len, + const void *seed2, int seed2_len, + const void *seed3, int seed3_len, + unsigned char *out, int olen) +{ + unsigned char out2[104]; + int i, len; + + if (olen > (int)sizeof(out2)) + return 0; + + len = sizeof(master_secret) / 2; + + if (!tls1_P_hash(EVP_md5(), master_secret, len, + seed1, seed1_len, seed2, seed2_len, seed3, + seed3_len, out, olen)) + return 0; + + if (!tls1_P_hash(EVP_sha1(), master_secret + len, len, + seed1, seed1_len, seed2, seed2_len, seed3, + seed3_len, out2, olen)) + return 0; + + for (i = 0; i < olen; i++) { + out[i] ^= out2[i]; + } + + return 1; +} + +static SSL_SESSION *client_session(void) +{ + static unsigned char session_asn1[] = { + 0x30, 0x5F, /* SEQUENCE, length 0x5F */ + 0x02, 0x01, 0x01, /* INTEGER, SSL_SESSION_ASN1_VERSION */ + 0x02, 0x02, 0x01, 0x00, /* INTEGER, DTLS1_BAD_VER */ + 0x04, 0x02, 0x00, 0x2F, /* OCTET_STRING, AES128-SHA */ + 0x04, 0x20, /* OCTET_STRING, session id */ +#define SS_SESSID_OFS 15 /* Session ID goes here */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x30, /* OCTET_STRING, master secret */ +#define SS_SECRET_OFS 49 /* Master secret goes here */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + const unsigned char *p = session_asn1; + + /* Copy the randomly-generated fields into the above ASN1 */ + memcpy(session_asn1 + SS_SESSID_OFS, session_id, sizeof(session_id)); + memcpy(session_asn1 + SS_SECRET_OFS, master_secret, sizeof(master_secret)); + + return d2i_SSL_SESSION(NULL, &p, sizeof(session_asn1)); +} + +/* Returns 1 for initial ClientHello, 2 for ClientHello with cookie */ +static int validate_client_hello(BIO *wbio) +{ + PACKET pkt, pkt2; + long len; + unsigned char *data; + int cookie_found = 0; + unsigned int u; + + len = BIO_get_mem_data(wbio, (char **)&data); + if (!PACKET_buf_init(&pkt, data, len)) + return 0; + + /* Check record header type */ + if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_HANDSHAKE) + return 0; + /* Version */ + if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER) + return 0; + /* Skip the rest of the record header */ + if (!PACKET_forward(&pkt, DTLS1_RT_HEADER_LENGTH - 3)) + return 0; + + /* Check it's a ClientHello */ + if (!PACKET_get_1(&pkt, &u) || u != SSL3_MT_CLIENT_HELLO) + return 0; + /* Skip the rest of the handshake message header */ + if (!PACKET_forward(&pkt, DTLS1_HM_HEADER_LENGTH - 1)) + return 0; + + /* Check client version */ + if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER) + return 0; + + /* Store random */ + if (!PACKET_copy_bytes(&pkt, client_random, SSL3_RANDOM_SIZE)) + return 0; + + /* Check session id length and content */ + if (!PACKET_get_length_prefixed_1(&pkt, &pkt2) || + !PACKET_equal(&pkt2, session_id, sizeof(session_id))) + return 0; + + /* Check cookie */ + if (!PACKET_get_length_prefixed_1(&pkt, &pkt2)) + return 0; + if (PACKET_remaining(&pkt2)) { + if (!PACKET_equal(&pkt2, cookie, sizeof(cookie))) + return 0; + cookie_found = 1; + } + + /* Skip ciphers */ + if (!PACKET_get_net_2(&pkt, &u) || !PACKET_forward(&pkt, u)) + return 0; + + /* Skip compression */ + if (!PACKET_get_1(&pkt, &u) || !PACKET_forward(&pkt, u)) + return 0; + + /* Skip extensions */ + if (!PACKET_get_net_2(&pkt, &u) || !PACKET_forward(&pkt, u)) + return 0; + + /* Now we are at the end */ + if (PACKET_remaining(&pkt)) + return 0; + + /* Update handshake MAC for second ClientHello (with cookie) */ + if (cookie_found && (!EVP_DigestUpdate(&handshake_md5, data + MAC_OFFSET, + len - MAC_OFFSET) || + !EVP_DigestUpdate(&handshake_sha1, data + MAC_OFFSET, + len - MAC_OFFSET))) + printf("EVP_DigestUpdate() failed\n"); + + (void)BIO_reset(wbio); + + return 1 + cookie_found; +} + +static int send_hello_verify(BIO *rbio) +{ + static unsigned char hello_verify[] = { + 0x16, /* Handshake */ + 0x01, 0x00, /* DTLS1_BAD_VER */ + 0x00, 0x00, /* Epoch 0 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Seq# 0 */ + 0x00, 0x23, /* Length */ + 0x03, /* Hello Verify */ + 0x00, 0x00, 0x17, /* Length */ + 0x00, 0x00, /* Seq# 0 */ + 0x00, 0x00, 0x00, /* Fragment offset */ + 0x00, 0x00, 0x17, /* Fragment length */ + 0x01, 0x00, /* DTLS1_BAD_VER */ + 0x14, /* Cookie length */ +#define HV_COOKIE_OFS 28 /* Cookie goes here */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + }; + + memcpy(hello_verify + HV_COOKIE_OFS, cookie, sizeof(cookie)); + + BIO_write(rbio, hello_verify, sizeof(hello_verify)); + + return 1; +} + +static int send_server_hello(BIO *rbio) +{ + static unsigned char server_hello[] = { + 0x16, /* Handshake */ + 0x01, 0x00, /* DTLS1_BAD_VER */ + 0x00, 0x00, /* Epoch 0 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, /* Seq# 1 */ + 0x00, 0x52, /* Length */ + 0x02, /* Server Hello */ + 0x00, 0x00, 0x46, /* Length */ + 0x00, 0x01, /* Seq# */ + 0x00, 0x00, 0x00, /* Fragment offset */ + 0x00, 0x00, 0x46, /* Fragment length */ + 0x01, 0x00, /* DTLS1_BAD_VER */ +#define SH_RANDOM_OFS 27 /* Server random goes here */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x20, /* Session ID length */ +#define SH_SESSID_OFS 60 /* Session ID goes here */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x2f, /* Cipher suite AES128-SHA */ + 0x00, /* Compression null */ + }; + static unsigned char change_cipher_spec[] = { + 0x14, /* Change Cipher Spec */ + 0x01, 0x00, /* DTLS1_BAD_VER */ + 0x00, 0x00, /* Epoch 0 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, /* Seq# 2 */ + 0x00, 0x03, /* Length */ + 0x01, 0x00, 0x02, /* Message */ + }; + + memcpy(server_hello + SH_RANDOM_OFS, server_random, sizeof(server_random)); + memcpy(server_hello + SH_SESSID_OFS, session_id, sizeof(session_id)); + + if (!EVP_DigestUpdate(&handshake_md5, server_hello + MAC_OFFSET, + sizeof(server_hello) - MAC_OFFSET) || + !EVP_DigestUpdate(&handshake_sha1, server_hello + MAC_OFFSET, + sizeof(server_hello) - MAC_OFFSET)) + printf("EVP_DigestUpdate() failed\n"); + + BIO_write(rbio, server_hello, sizeof(server_hello)); + BIO_write(rbio, change_cipher_spec, sizeof(change_cipher_spec)); + + return 1; +} + +/* Create header, HMAC, pad, encrypt and send a record */ +static int send_record(BIO *rbio, unsigned char type, unsigned long seqnr, + const void *msg, size_t len) +{ + /* Note that the order of the record header fields on the wire, + * and in the HMAC, is different. So we just keep them in separate + * variables and handle them individually. */ + static unsigned char epoch[2] = { 0x00, 0x01 }; + static unsigned char seq[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + static unsigned char ver[2] = { 0x01, 0x00 }; /* DTLS1_BAD_VER */ + unsigned char lenbytes[2]; + HMAC_CTX ctx; + EVP_CIPHER_CTX enc_ctx; + unsigned char iv[16]; + unsigned char pad; + unsigned char *enc; + +#ifdef SIXTY_FOUR_BIT_LONG + seq[0] = (seqnr >> 40) & 0xff; + seq[1] = (seqnr >> 32) & 0xff; +#endif + seq[2] = (seqnr >> 24) & 0xff; + seq[3] = (seqnr >> 16) & 0xff; + seq[4] = (seqnr >> 8) & 0xff; + seq[5] = seqnr & 0xff; + + pad = 15 - ((len + SHA_DIGEST_LENGTH) % 16); + enc = OPENSSL_malloc(len + SHA_DIGEST_LENGTH + 1 + pad); + if (enc == NULL) + return 0; + + /* Copy record to encryption buffer */ + memcpy(enc, msg, len); + + /* Append HMAC to data */ + HMAC_Init(&ctx, mac_key, 20, EVP_sha1()); + HMAC_Update(&ctx, epoch, 2); + HMAC_Update(&ctx, seq, 6); + HMAC_Update(&ctx, &type, 1); + HMAC_Update(&ctx, ver, 2); /* Version */ + lenbytes[0] = len >> 8; + lenbytes[1] = len & 0xff; + HMAC_Update(&ctx, lenbytes, 2); /* Length */ + HMAC_Update(&ctx, enc, len); /* Finally the data itself */ + HMAC_Final(&ctx, enc + len, NULL); + HMAC_CTX_cleanup(&ctx); + + /* Append padding bytes */ + len += SHA_DIGEST_LENGTH; + do { + enc[len++] = pad; + } while (len % 16); + + /* Generate IV, and encrypt */ + RAND_bytes(iv, sizeof(iv)); + EVP_CIPHER_CTX_init(&enc_ctx); + EVP_CipherInit_ex(&enc_ctx, EVP_aes_128_cbc(), NULL, enc_key, iv, 1); + EVP_Cipher(&enc_ctx, enc, enc, len); + EVP_CIPHER_CTX_cleanup(&enc_ctx); + + /* Finally write header (from fragmented variables), IV and encrypted record */ + BIO_write(rbio, &type, 1); + BIO_write(rbio, ver, 2); + BIO_write(rbio, epoch, 2); + BIO_write(rbio, seq, 6); + lenbytes[0] = (len + sizeof(iv)) >> 8; + lenbytes[1] = (len + sizeof(iv)) & 0xff; + BIO_write(rbio, lenbytes, 2); + + BIO_write(rbio, iv, sizeof(iv)); + BIO_write(rbio, enc, len); + + OPENSSL_free(enc); + return 1; +} + +static int send_finished(SSL *s, BIO *rbio) +{ + static unsigned char finished_msg[DTLS1_HM_HEADER_LENGTH + + TLS1_FINISH_MAC_LENGTH] = { + 0x14, /* Finished */ + 0x00, 0x00, 0x0c, /* Length */ + 0x00, 0x03, /* Seq# 3 */ + 0x00, 0x00, 0x00, /* Fragment offset */ + 0x00, 0x00, 0x0c, /* Fragment length */ + /* Finished MAC (12 bytes) */ + }; + unsigned char handshake_hash[EVP_MAX_MD_SIZE * 2]; + + /* Derive key material */ + do_PRF(TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE, + server_random, SSL3_RANDOM_SIZE, + client_random, SSL3_RANDOM_SIZE, + key_block, sizeof(key_block)); + + /* Generate Finished MAC */ + if (!EVP_DigestFinal_ex(&handshake_md5, handshake_hash, NULL) || + !EVP_DigestFinal_ex(&handshake_sha1, handshake_hash + EVP_MD_CTX_size(&handshake_md5), NULL)) + printf("EVP_DigestFinal_ex() failed\n"); + + do_PRF(TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE, + handshake_hash, EVP_MD_CTX_size(&handshake_md5) + EVP_MD_CTX_size(&handshake_sha1), + NULL, 0, + finished_msg + DTLS1_HM_HEADER_LENGTH, TLS1_FINISH_MAC_LENGTH); + + return send_record(rbio, SSL3_RT_HANDSHAKE, 0, + finished_msg, sizeof(finished_msg)); +} + +static int validate_ccs(BIO *wbio) +{ + PACKET pkt; + long len; + unsigned char *data; + unsigned int u; + + len = BIO_get_mem_data(wbio, (char **)&data); + if (!PACKET_buf_init(&pkt, data, len)) + return 0; + + /* Check record header type */ + if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_CHANGE_CIPHER_SPEC) + return 0; + /* Version */ + if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER) + return 0; + /* Skip the rest of the record header */ + if (!PACKET_forward(&pkt, DTLS1_RT_HEADER_LENGTH - 3)) + return 0; + + /* Check ChangeCipherSpec message */ + if (!PACKET_get_1(&pkt, &u) || u != SSL3_MT_CCS) + return 0; + /* A DTLS1_BAD_VER ChangeCipherSpec also contains the + * handshake sequence number (which is 2 here) */ + if (!PACKET_get_net_2(&pkt, &u) || u != 0x0002) + return 0; + + /* Now check the Finished packet */ + if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_HANDSHAKE) + return 0; + if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER) + return 0; + + /* Check epoch is now 1 */ + if (!PACKET_get_net_2(&pkt, &u) || u != 0x0001) + return 0; + + /* That'll do for now. If OpenSSL accepted *our* Finished packet + * then it's evidently remembered that DTLS1_BAD_VER doesn't + * include the handshake header in the MAC. There's not a lot of + * point in implementing decryption here, just to check that it + * continues to get it right for one more packet. */ + + return 1; +} + +#define NODROP(x) { x##UL, 0 } +#define DROP(x) { x##UL, 1 } + +static struct { + unsigned long seq; + int drop; +} tests[] = { + NODROP(1), NODROP(3), NODROP(2), + NODROP(0x1234), NODROP(0x1230), NODROP(0x1235), + NODROP(0xffff), NODROP(0x10001), NODROP(0xfffe), NODROP(0x10000), + DROP(0x10001), DROP(0xff), NODROP(0x100000), NODROP(0x800000), NODROP(0x7fffe1), + NODROP(0xffffff), NODROP(0x1000000), NODROP(0xfffffe), DROP(0xffffff), NODROP(0x1000010), + NODROP(0xfffffd), NODROP(0x1000011), DROP(0x12), NODROP(0x1000012), + NODROP(0x1ffffff), NODROP(0x2000000), DROP(0x1ff00fe), NODROP(0x2000001), + NODROP(0x20fffff), NODROP(0x2105500), DROP(0x20ffffe), NODROP(0x21054ff), + NODROP(0x211ffff), DROP(0x2110000), NODROP(0x2120000) + /* The last test should be NODROP, because a DROP wouldn't get tested. */ +}; + +int main(int argc, char *argv[]) +{ + SSL_SESSION *sess; + SSL_CTX *ctx; + SSL *con; + BIO *rbio; + BIO *wbio; + BIO *err; + int testresult = 0; + int ret; + int i; + + SSL_library_init(); + SSL_load_error_strings(); + + err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT); + + CRYPTO_malloc_debug_init(); + CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL); + CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); + + RAND_bytes(session_id, sizeof(session_id)); + RAND_bytes(master_secret, sizeof(master_secret)); + RAND_bytes(cookie, sizeof(cookie)); + RAND_bytes(server_random + 4, sizeof(server_random) - 4); + time((void *)server_random); + + sess = client_session(); + if (sess == NULL) { + printf("Failed to generate SSL_SESSION\n"); + goto end; + } + + if (!EVP_DigestInit_ex(&handshake_md5, EVP_md5(), NULL) || + !EVP_DigestInit_ex(&handshake_sha1, EVP_sha1(), NULL)) { + printf("Failed to initialise handshake_md\n"); + goto end; + } + + ctx = SSL_CTX_new(DTLSv1_client_method()); + if (ctx == NULL) { + printf("Failed to allocate SSL_CTX\n"); + goto end_md; + } + SSL_CTX_set_options(ctx, SSL_OP_CISCO_ANYCONNECT); + + if (!SSL_CTX_set_cipher_list(ctx, "AES128-SHA")) { + printf("SSL_CTX_set_cipher_list() failed\n"); + goto end_ctx; + } + + con = SSL_new(ctx); + if (!SSL_set_session(con, sess)) { + printf("SSL_set_session() failed\n"); + goto end_con; + } + SSL_SESSION_free(sess); + + rbio = BIO_new(BIO_s_mem()); + wbio = BIO_new(BIO_s_mem()); + + BIO_set_nbio(rbio, 1); + BIO_set_nbio(wbio, 1); + + SSL_set_bio(con, rbio, wbio); + SSL_set_connect_state(con); + + /* Send initial ClientHello */ + ret = SSL_do_handshake(con); + if (ret > 0 || SSL_get_error(con, ret) != SSL_ERROR_WANT_READ) { + printf("Unexpected handshake result at initial call!\n"); + goto end_con; + } + + if (validate_client_hello(wbio) != 1) { + printf("Initial ClientHello failed validation\n"); + goto end_con; + } + if (send_hello_verify(rbio) != 1) { + printf("Failed to send HelloVerify\n"); + goto end_con; + } + ret = SSL_do_handshake(con); + if (ret > 0 || SSL_get_error(con, ret) != SSL_ERROR_WANT_READ) { + printf("Unexpected handshake result after HelloVerify!\n"); + goto end_con; + } + if (validate_client_hello(wbio) != 2) { + printf("Second ClientHello failed validation\n"); + goto end_con; + } + if (send_server_hello(rbio) != 1) { + printf("Failed to send ServerHello\n"); + goto end_con; + } + ret = SSL_do_handshake(con); + if (ret > 0 || SSL_get_error(con, ret) != SSL_ERROR_WANT_READ) { + printf("Unexpected handshake result after ServerHello!\n"); + goto end_con; + } + if (send_finished(con, rbio) != 1) { + printf("Failed to send Finished\n"); + goto end_con; + } + ret = SSL_do_handshake(con); + if (ret < 1) { + printf("Handshake not successful after Finished!\n"); + goto end_con; + } + if (validate_ccs(wbio) != 1) { + printf("Failed to validate client CCS/Finished\n"); + goto end_con; + } + + /* While we're here and crafting packets by hand, we might as well do a + bit of a stress test on the DTLS record replay handling. Not Cisco-DTLS + specific but useful anyway for the general case. It's been broken + before, and in fact was broken even for a basic 0, 2, 1 test case + when this test was first added.... */ + for (i = 0; i < (int)OSSL_NELEM(tests); i++) { + unsigned long recv_buf[2]; + + if (send_record(rbio, SSL3_RT_APPLICATION_DATA, tests[i].seq, + &tests[i].seq, sizeof(unsigned long)) != 1) { + printf("Failed to send data seq #0x%lx (%d)\n", + tests[i].seq, i); + goto end_con; + } + + if (tests[i].drop) + continue; + + ret = SSL_read(con, recv_buf, 2 * sizeof(unsigned long)); + if (ret != sizeof(unsigned long)) { + printf("SSL_read failed or wrong size on seq#0x%lx (%d)\n", + tests[i].seq, i); + goto end_con; + } + if (recv_buf[0] != tests[i].seq) { + printf("Wrong data packet received (0x%lx not 0x%lx) at packet %d\n", + recv_buf[0], tests[i].seq, i); + goto end_con; + } + } + if (tests[i-1].drop) { + printf("Error: last test cannot be DROP()\n"); + goto end_con; + } + testresult=1; + + end_con: + SSL_free(con); + end_ctx: + SSL_CTX_free(ctx); + end_md: + EVP_MD_CTX_cleanup(&handshake_md5); + EVP_MD_CTX_cleanup(&handshake_sha1); + end: + ERR_print_errors_fp(stderr); + + if (!testresult) { + printf("Cisco BadDTLS test: FAILED\n"); + } + + ERR_free_strings(); + ERR_remove_thread_state(NULL); + EVP_cleanup(); + CRYPTO_cleanup_all_ex_data(); + CRYPTO_mem_leaks(err); + BIO_free(err); + + return testresult?0:1; +} diff --git a/ssl/d1_both.c b/ssl/d1_both.c index 5d26c949265f..9bc61536101b 100644 --- a/ssl/d1_both.c +++ b/ssl/d1_both.c @@ -581,9 +581,12 @@ static int dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr, /* * msg_len is limited to 2^24, but is effectively checked against max * above + * + * Make buffer slightly larger than message length as a precaution + * against small OOB reads e.g. CVE-2016-6306 */ if (!BUF_MEM_grow_clean - (s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) { + (s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH + 16)) { SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, ERR_R_BUF_LIB); return SSL_AD_INTERNAL_ERROR; } @@ -618,11 +621,23 @@ static int dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok) int al; *ok = 0; - item = pqueue_peek(s->d1->buffered_messages); - if (item == NULL) - return 0; + do { + item = pqueue_peek(s->d1->buffered_messages); + if (item == NULL) + return 0; + + frag = (hm_fragment *)item->data; + + if (frag->msg_header.seq < s->d1->handshake_read_seq) { + /* This is a stale message that has been buffered so clear it */ + pqueue_pop(s->d1->buffered_messages); + dtls1_hm_fragment_free(frag); + pitem_free(item); + item = NULL; + frag = NULL; + } + } while (item == NULL); - frag = (hm_fragment *)item->data; /* Don't return if reassembly still in progress */ if (frag->reassembly != NULL) @@ -1211,7 +1226,7 @@ dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off, unsigned long header_length; unsigned char seq64be[8]; struct dtls1_retransmit_state saved_state; - unsigned char save_write_sequence[8]; + unsigned char save_write_sequence[8] = {0, 0, 0, 0, 0, 0, 0, 0}; /*- OPENSSL_assert(s->init_num == 0); @@ -1296,18 +1311,6 @@ dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off, return ret; } -/* call this function when the buffered messages are no longer needed */ -void dtls1_clear_record_buffer(SSL *s) -{ - pitem *item; - - for (item = pqueue_pop(s->d1->sent_messages); - item != NULL; item = pqueue_pop(s->d1->sent_messages)) { - dtls1_hm_fragment_free((hm_fragment *)item->data); - pitem_free(item); - } -} - unsigned char *dtls1_set_message_header(SSL *s, unsigned char *p, unsigned char mt, unsigned long len, unsigned long frag_off, @@ -1469,7 +1472,7 @@ int dtls1_process_heartbeat(SSL *s) memcpy(bp, pl, payload); bp += payload; /* Random padding */ - if (RAND_pseudo_bytes(bp, padding) < 0) { + if (RAND_bytes(bp, padding) <= 0) { OPENSSL_free(buffer); return -1; } @@ -1546,6 +1549,8 @@ int dtls1_heartbeat(SSL *s) * - Padding */ buf = OPENSSL_malloc(1 + 2 + payload + padding); + if (buf == NULL) + goto err; p = buf; /* Message Type */ *p++ = TLS1_HB_REQUEST; @@ -1554,11 +1559,11 @@ int dtls1_heartbeat(SSL *s) /* Sequence number */ s2n(s->tlsext_hb_seq, p); /* 16 random bytes */ - if (RAND_pseudo_bytes(p, 16) < 0) + if (RAND_bytes(p, 16) <= 0) goto err; p += 16; /* Random padding */ - if (RAND_pseudo_bytes(p, padding) < 0) + if (RAND_bytes(p, padding) <= 0) goto err; ret = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding); diff --git a/ssl/d1_clnt.c b/ssl/d1_clnt.c index 3ddfa7bca4b7..7e2f5c2830b5 100644 --- a/ssl/d1_clnt.c +++ b/ssl/d1_clnt.c @@ -769,6 +769,7 @@ int dtls1_connect(SSL *s) /* done with handshaking */ s->d1->handshake_read_seq = 0; s->d1->next_handshake_write_seq = 0; + dtls1_clear_received_buffer(s); goto end; /* break; */ diff --git a/ssl/d1_lib.c b/ssl/d1_lib.c index ee78921ba8b0..debd4fd5dcca 100644 --- a/ssl/d1_lib.c +++ b/ssl/d1_lib.c @@ -170,7 +170,6 @@ int dtls1_new(SSL *s) static void dtls1_clear_queues(SSL *s) { pitem *item = NULL; - hm_fragment *frag = NULL; DTLS1_RECORD_DATA *rdata; while ((item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL) { @@ -191,28 +190,44 @@ static void dtls1_clear_queues(SSL *s) pitem_free(item); } + while ((item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL) { + rdata = (DTLS1_RECORD_DATA *)item->data; + if (rdata->rbuf.buf) { + OPENSSL_free(rdata->rbuf.buf); + } + OPENSSL_free(item->data); + pitem_free(item); + } + + dtls1_clear_received_buffer(s); + dtls1_clear_sent_buffer(s); +} + +void dtls1_clear_received_buffer(SSL *s) +{ + pitem *item = NULL; + hm_fragment *frag = NULL; + while ((item = pqueue_pop(s->d1->buffered_messages)) != NULL) { frag = (hm_fragment *)item->data; dtls1_hm_fragment_free(frag); pitem_free(item); } +} + +void dtls1_clear_sent_buffer(SSL *s) +{ + pitem *item = NULL; + hm_fragment *frag = NULL; while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; dtls1_hm_fragment_free(frag); pitem_free(item); } - - while ((item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL) { - rdata = (DTLS1_RECORD_DATA *)item->data; - if (rdata->rbuf.buf) { - OPENSSL_free(rdata->rbuf.buf); - } - OPENSSL_free(item->data); - pitem_free(item); - } } + void dtls1_free(SSL *s) { ssl3_free(s); @@ -456,7 +471,7 @@ void dtls1_stop_timer(SSL *s) BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &(s->d1->next_timeout)); /* Clear retransmission buffer */ - dtls1_clear_record_buffer(s); + dtls1_clear_sent_buffer(s); } int dtls1_check_timeout_num(SSL *s) diff --git a/ssl/d1_pkt.c b/ssl/d1_pkt.c index fe30ec7d0042..7a02459f2b78 100644 --- a/ssl/d1_pkt.c +++ b/ssl/d1_pkt.c @@ -125,7 +125,7 @@ /* mod 128 saturating subtract of two 64-bit values in big-endian order */ static int satsub64be(const unsigned char *v1, const unsigned char *v2) { - int ret, sat, brw, i; + int ret, i; if (sizeof(long) == 8) do { @@ -157,28 +157,51 @@ static int satsub64be(const unsigned char *v1, const unsigned char *v2) return (int)l; } while (0); - ret = (int)v1[7] - (int)v2[7]; - sat = 0; - brw = ret >> 8; /* brw is either 0 or -1 */ - if (ret & 0x80) { - for (i = 6; i >= 0; i--) { - brw += (int)v1[i] - (int)v2[i]; - sat |= ~brw; - brw >>= 8; - } - } else { - for (i = 6; i >= 0; i--) { - brw += (int)v1[i] - (int)v2[i]; - sat |= brw; - brw >>= 8; + ret = 0; + for (i=0; i<7; i++) { + if (v1[i] > v2[i]) { + /* v1 is larger... but by how much? */ + if (v1[i] != v2[i] + 1) + return 128; + while (++i <= 6) { + if (v1[i] != 0x00 || v2[i] != 0xff) + return 128; /* too much */ + } + /* We checked all the way to the penultimate byte, + * so despite higher bytes changing we actually + * know that it only changed from (e.g.) + * ... (xx) ff ff ff ?? + * to ... (xx+1) 00 00 00 ?? + * so we add a 'bias' of 256 for the carry that + * happened, and will eventually return + * 256 + v1[7] - v2[7]. */ + ret = 256; + break; + } else if (v2[i] > v1[i]) { + /* v2 is larger... but by how much? */ + if (v2[i] != v1[i] + 1) + return -128; + while (++i <= 6) { + if (v2[i] != 0x00 || v1[i] != 0xff) + return -128; /* too much */ + } + /* Similar to the case above, we know it changed + * from ... (xx) 00 00 00 ?? + * to ... (xx-1) ff ff ff ?? + * so we add a 'bias' of -256 for the borrow, + * to return -256 + v1[7] - v2[7]. */ + ret = -256; } } - brw <<= 8; /* brw is either 0 or -256 */ - if (sat & 0xff) - return brw | 0x80; + ret += (int)v1[7] - (int)v2[7]; + + if (ret > 128) + return 128; + else if (ret < -128) + return -128; else - return brw + (ret & 0xFF); + return ret; } static int have_handshake_fragment(SSL *s, int type, unsigned char *buf, @@ -194,7 +217,7 @@ static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, #endif static int dtls1_buffer_record(SSL *s, record_pqueue *q, unsigned char *priority); -static int dtls1_process_record(SSL *s); +static int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap); /* copy buffered record into SSL structure */ static int dtls1_copy_record(SSL *s, pitem *item) @@ -319,21 +342,70 @@ static int dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue) static int dtls1_process_buffered_records(SSL *s) { pitem *item; + SSL3_BUFFER *rb; + SSL3_RECORD *rr; + DTLS1_BITMAP *bitmap; + unsigned int is_next_epoch; + int replayok = 1; item = pqueue_peek(s->d1->unprocessed_rcds.q); if (item) { /* Check if epoch is current. */ if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch) - return (1); /* Nothing to do. */ + return 1; /* Nothing to do. */ + + rr = &s->s3->rrec; + rb = &s->s3->rbuf; + + if (rb->left > 0) { + /* + * We've still got data from the current packet to read. There could + * be a record from the new epoch in it - so don't overwrite it + * with the unprocessed records yet (we'll do it when we've + * finished reading the current packet). + */ + return 1; + } + /* Process all the records. */ while (pqueue_peek(s->d1->unprocessed_rcds.q)) { dtls1_get_unprocessed_record(s); - if (!dtls1_process_record(s)) - return (0); + bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch); + if (bitmap == NULL) { + /* + * Should not happen. This will only ever be NULL when the + * current record is from a different epoch. But that cannot + * be the case because we already checked the epoch above + */ + SSLerr(SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS, + ERR_R_INTERNAL_ERROR); + return 0; + } +#ifndef OPENSSL_NO_SCTP + /* Only do replay check if no SCTP bio */ + if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) +#endif + { + /* + * Check whether this is a repeat, or aged record. We did this + * check once already when we first received the record - but + * we might have updated the window since then due to + * records we subsequently processed. + */ + replayok = dtls1_record_replay_check(s, bitmap); + } + + if (!replayok || !dtls1_process_record(s, bitmap)) { + /* dump this record */ + rr->length = 0; + s->packet_length = 0; + continue; + } + if (dtls1_buffer_record(s, &(s->d1->processed_rcds), s->s3->rrec.seq_num) < 0) - return -1; + return 0; } } @@ -344,7 +416,7 @@ static int dtls1_process_buffered_records(SSL *s) s->d1->processed_rcds.epoch = s->d1->r_epoch; s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1; - return (1); + return 1; } #if 0 @@ -391,7 +463,7 @@ static int dtls1_get_buffered_record(SSL *s) #endif -static int dtls1_process_record(SSL *s) +static int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap) { int i, al; int enc_err; @@ -551,6 +623,10 @@ static int dtls1_process_record(SSL *s) /* we have pulled in a full packet so zero things */ s->packet_length = 0; + + /* Mark receipt of record. */ + dtls1_record_bitmap_update(s, bitmap); + return (1); f_err: @@ -581,11 +657,12 @@ int dtls1_get_record(SSL *s) rr = &(s->s3->rrec); + again: /* * The epoch may have changed. If so, process all the pending records. * This is a non-blocking operation. */ - if (dtls1_process_buffered_records(s) < 0) + if (!dtls1_process_buffered_records(s)) return -1; /* if we're renegotiating, then there may be buffered records */ @@ -593,7 +670,6 @@ int dtls1_get_record(SSL *s) return 1; /* get something from the wire */ - again: /* check if we have the header */ if ((s->rstate != SSL_ST_READ_BODY) || (s->packet_length < DTLS1_RT_HEADER_LENGTH)) { @@ -721,20 +797,17 @@ int dtls1_get_record(SSL *s) if (dtls1_buffer_record (s, &(s->d1->unprocessed_rcds), rr->seq_num) < 0) return -1; - /* Mark receipt of record. */ - dtls1_record_bitmap_update(s, bitmap); } rr->length = 0; s->packet_length = 0; goto again; } - if (!dtls1_process_record(s)) { + if (!dtls1_process_record(s, bitmap)) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } - dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */ return (1); @@ -878,6 +951,13 @@ int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) goto start; } + /* + * Reset the count of consecutive warning alerts if we've got a non-empty + * record that isn't an alert. + */ + if (rr->type != SSL3_RT_ALERT && rr->length != 0) + s->cert->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, @@ -1144,6 +1224,14 @@ int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) if (alert_level == SSL3_AL_WARNING) { s->s3->warn_alert = alert_descr; + + s->cert->alert_count++; + if (s->cert->alert_count == MAX_WARN_ALERT_COUNT) { + al = SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS); + goto f_err; + } + if (alert_descr == SSL_AD_CLOSE_NOTIFY) { #ifndef OPENSSL_NO_SCTP /* @@ -1201,7 +1289,7 @@ int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr); ERR_add_error_data(2, "SSL alert number ", tmp); s->shutdown |= SSL_RECEIVED_SHUTDOWN; - SSL_CTX_remove_session(s->ctx, s->session); + SSL_CTX_remove_session(s->session_ctx, s->session); return (0); } else { al = SSL_AD_ILLEGAL_PARAMETER; @@ -1830,8 +1918,13 @@ static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, if (rr->epoch == s->d1->r_epoch) return &s->d1->bitmap; - /* Only HM and ALERT messages can be from the next epoch */ + /* + * Only HM and ALERT messages can be from the next epoch and only if we + * have already processed all of the unprocessed records from the last + * epoch + */ else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) && + s->d1->unprocessed_rcds.epoch != s->d1->r_epoch && (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) { *is_next_epoch = 1; return &s->d1->next_bitmap; @@ -1910,6 +2003,12 @@ void dtls1_reset_seq_numbers(SSL *s, int rw) s->d1->r_epoch++; memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP)); memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP)); + + /* + * We must not use any buffered messages received from the previous + * epoch + */ + dtls1_clear_received_buffer(s); } else { seq = s->s3->write_sequence; memcpy(s->d1->last_write_sequence, seq, diff --git a/ssl/d1_srvr.c b/ssl/d1_srvr.c index e677d880f0ac..bc875b53c9a0 100644 --- a/ssl/d1_srvr.c +++ b/ssl/d1_srvr.c @@ -313,7 +313,7 @@ int dtls1_accept(SSL *s) case SSL3_ST_SW_HELLO_REQ_B: s->shutdown = 0; - dtls1_clear_record_buffer(s); + dtls1_clear_sent_buffer(s); dtls1_start_timer(s); ret = ssl3_send_hello_request(s); if (ret <= 0) @@ -894,6 +894,7 @@ int dtls1_accept(SSL *s) /* next message is server hello */ s->d1->handshake_write_seq = 0; s->d1->next_handshake_write_seq = 0; + dtls1_clear_received_buffer(s); goto end; /* break; */ diff --git a/ssl/dtlstest.c b/ssl/dtlstest.c new file mode 100644 index 000000000000..78ebc67744c4 --- /dev/null +++ b/ssl/dtlstest.c @@ -0,0 +1,147 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include <openssl/bio.h> +#include <openssl/crypto.h> +#include <openssl/ssl.h> +#include <openssl/err.h> + +#include "ssltestlib.h" +#include "testutil.h" + +static char *cert = NULL; +static char *privkey = NULL; + +#define NUM_TESTS 2 + + +#define DUMMY_CERT_STATUS_LEN 12 + +unsigned char certstatus[] = { + SSL3_RT_HANDSHAKE, /* Content type */ + 0xfe, 0xfd, /* Record version */ + 0, 1, /* Epoch */ + 0, 0, 0, 0, 0, 0x0f, /* Record sequence number */ + 0, DTLS1_HM_HEADER_LENGTH + DUMMY_CERT_STATUS_LEN - 2, + SSL3_MT_CERTIFICATE_STATUS, /* Cert Status handshake message type */ + 0, 0, DUMMY_CERT_STATUS_LEN, /* Message len */ + 0, 5, /* Message sequence */ + 0, 0, 0, /* Fragment offset */ + 0, 0, DUMMY_CERT_STATUS_LEN - 2, /* Fragment len */ + 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x80 /* Dummy data */ +}; + +#define RECORD_SEQUENCE 10 + +static int test_dtls_unprocessed(int testidx) +{ + SSL_CTX *sctx = NULL, *cctx = NULL; + SSL *serverssl1 = NULL, *clientssl1 = NULL; + BIO *c_to_s_fbio, *c_to_s_mempacket; + int testresult = 0; + + printf("Starting Test %d\n", testidx); + + if (!create_ssl_ctx_pair(DTLS_server_method(), DTLS_client_method(), &sctx, + &cctx, cert, privkey)) { + printf("Unable to create SSL_CTX pair\n"); + return 0; + } + + if (!SSL_CTX_set_ecdh_auto(sctx, 1)) { + printf("Failed configuring auto ECDH\n"); + } + + if (!SSL_CTX_set_cipher_list(cctx, "AES128-SHA")) { + printf("Failed setting cipher list\n"); + } + + c_to_s_fbio = BIO_new(bio_f_tls_dump_filter()); + if (c_to_s_fbio == NULL) { + printf("Failed to create filter BIO\n"); + goto end; + } + + /* BIO is freed by create_ssl_connection on error */ + if (!create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1, NULL, + c_to_s_fbio)) { + printf("Unable to create SSL objects\n"); + ERR_print_errors_fp(stdout); + goto end; + } + + if (testidx == 1) + certstatus[RECORD_SEQUENCE] = 0xff; + + /* + * Inject a dummy record from the next epoch. In test 0, this should never + * get used because the message sequence number is too big. In test 1 we set + * the record sequence number to be way off in the future. This should not + * have an impact on the record replay protection because the record should + * be dropped before it is marked as arrivedg + */ + c_to_s_mempacket = SSL_get_wbio(clientssl1); + c_to_s_mempacket = BIO_next(c_to_s_mempacket); + mempacket_test_inject(c_to_s_mempacket, (char *)certstatus, + sizeof(certstatus), 1, INJECT_PACKET_IGNORE_REC_SEQ); + + if (!create_ssl_connection(serverssl1, clientssl1)) { + printf("Unable to create SSL connection\n"); + ERR_print_errors_fp(stdout); + goto end; + } + + testresult = 1; + end: + SSL_free(serverssl1); + SSL_free(clientssl1); + SSL_CTX_free(sctx); + SSL_CTX_free(cctx); + + return testresult; +} + +int main(int argc, char *argv[]) +{ + BIO *err = NULL; + int testresult = 0; + + if (argc != 3) { + printf("Invalid argument count\n"); + return 1; + } + + cert = argv[1]; + privkey = argv[2]; + + err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT); + + SSL_library_init(); + SSL_load_error_strings(); + + CRYPTO_malloc_debug_init(); + CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL); + CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); + + if (!test_dtls_unprocessed(0) || !test_dtls_unprocessed(1)) + testresult = 1; + + ERR_free_strings(); + ERR_remove_thread_state(NULL); + EVP_cleanup(); + CRYPTO_cleanup_all_ex_data(); + CRYPTO_mem_leaks(err); + BIO_free(err); + + if (!testresult) + printf("PASS\n"); + + return testresult; +} diff --git a/ssl/s23_clnt.c b/ssl/s23_clnt.c index f782010c4782..6850dc0c6704 100644 --- a/ssl/s23_clnt.c +++ b/ssl/s23_clnt.c @@ -289,9 +289,9 @@ int ssl_fill_hello_random(SSL *s, int server, unsigned char *result, int len) unsigned long Time = (unsigned long)time(NULL); unsigned char *p = result; l2n(Time, p); - return RAND_pseudo_bytes(p, len - 4); + return RAND_bytes(p, len - 4); } else - return RAND_pseudo_bytes(result, len); + return RAND_bytes(result, len); } static int ssl23_client_hello(SSL *s) @@ -466,8 +466,8 @@ static int ssl23_client_hello(SSL *s) i = ch_len; s2n(i, d); memset(&(s->s3->client_random[0]), 0, SSL3_RANDOM_SIZE); - if (RAND_pseudo_bytes - (&(s->s3->client_random[SSL3_RANDOM_SIZE - i]), i) <= 0) + if (RAND_bytes (&(s->s3->client_random[SSL3_RANDOM_SIZE - i]), i) + <= 0) return -1; memcpy(p, &(s->s3->client_random[SSL3_RANDOM_SIZE - i]), i); diff --git a/ssl/s2_clnt.c b/ssl/s2_clnt.c index 69da6b1421df..20de1a82178f 100644 --- a/ssl/s2_clnt.c +++ b/ssl/s2_clnt.c @@ -581,7 +581,7 @@ static int client_hello(SSL *s) /* * challenge id data */ - if (RAND_pseudo_bytes(s->s2->challenge, SSL2_CHALLENGE_LENGTH) <= 0) + if (RAND_bytes(s->s2->challenge, SSL2_CHALLENGE_LENGTH) <= 0) return -1; memcpy(d, s->s2->challenge, SSL2_CHALLENGE_LENGTH); d += SSL2_CHALLENGE_LENGTH; @@ -629,7 +629,7 @@ static int client_master_key(SSL *s) return -1; } if (i > 0) - if (RAND_pseudo_bytes(sess->key_arg, i) <= 0) + if (RAND_bytes(sess->key_arg, i) <= 0) return -1; /* make a master key */ diff --git a/ssl/s2_srvr.c b/ssl/s2_srvr.c index 07e9df82820a..d3b243c27e02 100644 --- a/ssl/s2_srvr.c +++ b/ssl/s2_srvr.c @@ -526,11 +526,8 @@ static int get_client_master_key(SSL *s) * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */ - /* - * should be RAND_bytes, but we cannot work around a failure. - */ - if (RAND_pseudo_bytes(rand_premaster_secret, - (int)num_encrypted_key_bytes) <= 0) + if (RAND_bytes(rand_premaster_secret, + (int)num_encrypted_key_bytes) <= 0) return 0; i = ssl_rsa_private_decrypt(s->cert, s->s2->tmp.enc, @@ -822,8 +819,7 @@ static int server_hello(SSL *s) /* make and send conn_id */ s2n(SSL2_CONNECTION_ID_LENGTH, p); /* add conn_id length */ s->s2->conn_id_length = SSL2_CONNECTION_ID_LENGTH; - if (RAND_pseudo_bytes(s->s2->conn_id, (int)s->s2->conn_id_length) <= - 0) + if (RAND_bytes(s->s2->conn_id, (int)s->s2->conn_id_length) <= 0) return -1; memcpy(d, s->s2->conn_id, SSL2_CONNECTION_ID_LENGTH); d += SSL2_CONNECTION_ID_LENGTH; @@ -962,7 +958,7 @@ static int request_certificate(SSL *s) p = (unsigned char *)s->init_buf->data; *(p++) = SSL2_MT_REQUEST_CERTIFICATE; *(p++) = SSL2_AT_MD5_WITH_RSA_ENCRYPTION; - if (RAND_pseudo_bytes(ccd, SSL2_MIN_CERT_CHALLENGE_LENGTH) <= 0) + if (RAND_bytes(ccd, SSL2_MIN_CERT_CHALLENGE_LENGTH) <= 0) return -1; memcpy(p, ccd, SSL2_MIN_CERT_CHALLENGE_LENGTH); diff --git a/ssl/s3_both.c b/ssl/s3_both.c index 09d0661e81f6..054ded1c9903 100644 --- a/ssl/s3_both.c +++ b/ssl/s3_both.c @@ -356,21 +356,22 @@ long ssl3_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok) } *ok = 1; s->state = stn; - s->init_msg = s->init_buf->data + 4; + s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH; s->init_num = (int)s->s3->tmp.message_size; return s->init_num; } p = (unsigned char *)s->init_buf->data; - if (s->state == st1) { /* s->init_num < 4 */ + if (s->state == st1) { /* s->init_num < SSL3_HM_HEADER_LENGTH */ int skip_message; do { - while (s->init_num < 4) { + while (s->init_num < SSL3_HM_HEADER_LENGTH) { i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &p[s->init_num], - 4 - s->init_num, 0); + SSL3_HM_HEADER_LENGTH - + s->init_num, 0); if (i <= 0) { s->rwstate = SSL_READING; *ok = 0; @@ -394,12 +395,13 @@ long ssl3_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok) if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, - p, 4, s, s->msg_callback_arg); + p, SSL3_HM_HEADER_LENGTH, s, + s->msg_callback_arg); } } while (skip_message); - /* s->init_num == 4 */ + /* s->init_num == SSL3_HM_HEADER_LENGTH */ if ((mt >= 0) && (*p != mt)) { al = SSL_AD_UNEXPECTED_MESSAGE; @@ -415,19 +417,20 @@ long ssl3_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok) SSLerr(SSL_F_SSL3_GET_MESSAGE, SSL_R_EXCESSIVE_MESSAGE_SIZE); goto f_err; } - if (l > (INT_MAX - 4)) { /* BUF_MEM_grow takes an 'int' parameter */ - al = SSL_AD_ILLEGAL_PARAMETER; - SSLerr(SSL_F_SSL3_GET_MESSAGE, SSL_R_EXCESSIVE_MESSAGE_SIZE); - goto f_err; - } - if (l && !BUF_MEM_grow_clean(s->init_buf, (int)l + 4)) { + /* + * Make buffer slightly larger than message length as a precaution + * against small OOB reads e.g. CVE-2016-6306 + */ + if (l + && !BUF_MEM_grow_clean(s->init_buf, + (int)l + SSL3_HM_HEADER_LENGTH + 16)) { SSLerr(SSL_F_SSL3_GET_MESSAGE, ERR_R_BUF_LIB); goto err; } s->s3->tmp.message_size = l; s->state = stn; - s->init_msg = s->init_buf->data + 4; + s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH; s->init_num = 0; } @@ -456,10 +459,12 @@ long ssl3_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok) #endif /* Feed this message into MAC computation. */ - ssl3_finish_mac(s, (unsigned char *)s->init_buf->data, s->init_num + 4); + ssl3_finish_mac(s, (unsigned char *)s->init_buf->data, + s->init_num + SSL3_HM_HEADER_LENGTH); if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data, - (size_t)s->init_num + 4, s, s->msg_callback_arg); + (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s, + s->msg_callback_arg); *ok = 1; return s->init_num; f_err: @@ -535,6 +540,9 @@ int ssl_verify_alarm_type(long type) case X509_V_ERR_CRL_NOT_YET_VALID: case X509_V_ERR_CERT_UNTRUSTED: case X509_V_ERR_CERT_REJECTED: + case X509_V_ERR_HOSTNAME_MISMATCH: + case X509_V_ERR_EMAIL_MISMATCH: + case X509_V_ERR_IP_ADDRESS_MISMATCH: al = SSL_AD_BAD_CERTIFICATE; break; case X509_V_ERR_CERT_SIGNATURE_FAILURE: @@ -548,7 +556,10 @@ int ssl_verify_alarm_type(long type) case X509_V_ERR_CERT_REVOKED: al = SSL_AD_CERTIFICATE_REVOKED; break; + case X509_V_ERR_UNSPECIFIED: case X509_V_ERR_OUT_OF_MEM: + case X509_V_ERR_INVALID_CALL: + case X509_V_ERR_STORE_LOOKUP: al = SSL_AD_INTERNAL_ERROR; break; case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: diff --git a/ssl/s3_clnt.c b/ssl/s3_clnt.c index 19dc8648b952..218534734dd7 100644 --- a/ssl/s3_clnt.c +++ b/ssl/s3_clnt.c @@ -1216,6 +1216,12 @@ int ssl3_get_server_certificate(SSL *s) goto f_err; } for (nc = 0; nc < llen;) { + if (nc + 3 > llen) { + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, + SSL_R_CERT_LENGTH_MISMATCH); + goto f_err; + } n2l3(p, l); if ((l + nc + 3) > llen) { al = SSL_AD_DECODE_ERROR; @@ -2111,6 +2117,10 @@ int ssl3_get_certificate_request(SSL *s) if (ctype_num > SSL3_CT_NUMBER) { /* If we exceed static buffer copy all to cert structure */ s->cert->ctypes = OPENSSL_malloc(ctype_num); + if (s->cert->ctypes == NULL) { + SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE); + goto err; + } memcpy(s->cert->ctypes, p, ctype_num); s->cert->ctype_num = (size_t)ctype_num; ctype_num = SSL3_CT_NUMBER; @@ -2167,6 +2177,11 @@ int ssl3_get_certificate_request(SSL *s) } for (nc = 0; nc < llen;) { + if (nc + 2 > llen) { + ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR); + SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG); + goto err; + } n2s(p, l); if ((l + nc + 2) > llen) { if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) @@ -2999,19 +3014,6 @@ int ssl3_send_client_key_exchange(SSL *s) goto err; } /* - * If we have client certificate, use its secret as peer key - */ - if (s->s3->tmp.cert_req && s->cert->key->privatekey) { - if (EVP_PKEY_derive_set_peer - (pkey_ctx, s->cert->key->privatekey) <= 0) { - /* - * If there was an error - just ignore it. Ephemeral key - * * would be used - */ - ERR_clear_error(); - } - } - /* * Compute shared IV and store it in algorithm-specific context * data */ @@ -3057,12 +3059,6 @@ int ssl3_send_client_key_exchange(SSL *s) n = msglen + 2; } memcpy(p, tmp, msglen); - /* Check if pubkey from client certificate was used */ - if (EVP_PKEY_CTX_ctrl - (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) { - /* Set flag "skip certificate verify" */ - s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY; - } EVP_PKEY_CTX_free(pkey_ctx); s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, diff --git a/ssl/s3_enc.c b/ssl/s3_enc.c index 47a0ec9fe04b..fbc954d43c70 100644 --- a/ssl/s3_enc.c +++ b/ssl/s3_enc.c @@ -607,6 +607,10 @@ int ssl3_digest_cached_records(SSL *s) ssl3_free_digest_list(s); s->s3->handshake_dgst = OPENSSL_malloc(SSL_MAX_DIGEST * sizeof(EVP_MD_CTX *)); + if (s->s3->handshake_dgst == NULL) { + SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS, ERR_R_MALLOC_FAILURE); + return 0; + } memset(s->s3->handshake_dgst, 0, SSL_MAX_DIGEST * sizeof(EVP_MD_CTX *)); hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata); if (hdatalen <= 0) { @@ -624,8 +628,12 @@ int ssl3_digest_cached_records(SSL *s) EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); } #endif - EVP_DigestInit_ex(s->s3->handshake_dgst[i], md, NULL); - EVP_DigestUpdate(s->s3->handshake_dgst[i], hdata, hdatalen); + if (!EVP_DigestInit_ex(s->s3->handshake_dgst[i], md, NULL) + || !EVP_DigestUpdate(s->s3->handshake_dgst[i], hdata, + hdatalen)) { + SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS, ERR_R_INTERNAL_ERROR); + return 0; + } } else { s->s3->handshake_dgst[i] = NULL; } diff --git a/ssl/s3_lib.c b/ssl/s3_lib.c index 872e636af9e1..0385e039c8d4 100644 --- a/ssl/s3_lib.c +++ b/ssl/s3_lib.c @@ -329,7 +329,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_SSLV3, - SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -382,7 +382,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_SSLV3, - SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -434,7 +434,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_SSLV3, - SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -487,7 +487,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_SSLV3, - SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -539,7 +539,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_SSLV3, - SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -625,7 +625,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_SSLV3, - SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -712,7 +712,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_SSLV3, - SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -778,7 +778,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_MD5, SSL_SSLV3, - SSL_NOT_EXP | SSL_HIGH, + SSL_NOT_EXP | SSL_MEDIUM, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -1728,7 +1728,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_TLSV1, - SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -2120,7 +2120,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_TLSV1, - SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -2200,7 +2200,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_TLSV1, - SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -2280,7 +2280,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_TLSV1, - SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -2360,7 +2360,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_TLSV1, - SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -2440,7 +2440,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_TLSV1, - SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, + SSL_NOT_DEFAULT | SSL_NOT_EXP | SSL_MEDIUM | SSL_FIPS, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -2490,7 +2490,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_TLSV1, - SSL_NOT_EXP | SSL_HIGH, + SSL_NOT_EXP | SSL_MEDIUM, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -2506,7 +2506,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_TLSV1, - SSL_NOT_EXP | SSL_HIGH, + SSL_NOT_EXP | SSL_MEDIUM, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -2522,7 +2522,7 @@ OPENSSL_GLOBAL SSL_CIPHER ssl3_ciphers[] = { SSL_3DES, SSL_SHA1, SSL_TLSV1, - SSL_NOT_EXP | SSL_HIGH, + SSL_NOT_EXP | SSL_MEDIUM, SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF, 112, 168, @@ -4528,7 +4528,10 @@ int ssl3_renegotiate_check(SSL *s) */ long ssl_get_algorithm2(SSL *s) { - long alg2 = s->s3->tmp.new_cipher->algorithm2; + long alg2; + if (s->s3 == NULL || s->s3->tmp.new_cipher == NULL) + return -1; + alg2 = s->s3->tmp.new_cipher->algorithm2; if (s->method->ssl3_enc->enc_flags & SSL_ENC_FLAG_SHA256_PRF && alg2 == (SSL_HANDSHAKE_MAC_DEFAULT | TLS1_PRF)) return SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256; diff --git a/ssl/s3_pkt.c b/ssl/s3_pkt.c index 379890237e86..be37ef0e50d8 100644 --- a/ssl/s3_pkt.c +++ b/ssl/s3_pkt.c @@ -1229,6 +1229,13 @@ int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) return (ret); } + /* + * Reset the count of consecutive warning alerts if we've got a non-empty + * record that isn't an alert. + */ + if (rr->type != SSL3_RT_ALERT && rr->length != 0) + s->cert->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, @@ -1443,6 +1450,14 @@ int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) if (alert_level == SSL3_AL_WARNING) { s->s3->warn_alert = alert_descr; + + s->cert->alert_count++; + if (s->cert->alert_count == MAX_WARN_ALERT_COUNT) { + al = SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS); + goto f_err; + } + if (alert_descr == SSL_AD_CLOSE_NOTIFY) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return (0); @@ -1473,7 +1488,7 @@ int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr); ERR_add_error_data(2, "SSL alert number ", tmp); s->shutdown |= SSL_RECEIVED_SHUTDOWN; - SSL_CTX_remove_session(s->ctx, s->session); + SSL_CTX_remove_session(s->session_ctx, s->session); return (0); } else { al = SSL_AD_ILLEGAL_PARAMETER; @@ -1698,7 +1713,7 @@ int ssl3_send_alert(SSL *s, int level, int desc) return -1; /* If a fatal one, remove from cache */ if ((level == 2) && (s->session != NULL)) - SSL_CTX_remove_session(s->ctx, s->session); + SSL_CTX_remove_session(s->session_ctx, s->session); s->s3->alert_dispatch = 1; s->s3->send_alert[0] = level; diff --git a/ssl/s3_srvr.c b/ssl/s3_srvr.c index ab28702ee972..01ccd5d2ae78 100644 --- a/ssl/s3_srvr.c +++ b/ssl/s3_srvr.c @@ -980,7 +980,8 @@ int ssl3_get_client_hello(SSL *s) session_length = *(p + SSL3_RANDOM_SIZE); - if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) { + if (SSL3_RANDOM_SIZE + session_length + 1 + >= (unsigned int)((d + n) - p)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; @@ -998,7 +999,7 @@ int ssl3_get_client_hello(SSL *s) /* get the session-id */ j = *(p++); - if (p + j > d + n) { + if ((d + n) - p < j) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; @@ -1054,14 +1055,14 @@ int ssl3_get_client_hello(SSL *s) if (SSL_IS_DTLS(s)) { /* cookie stuff */ - if (p + 1 > d + n) { + if ((d + n) - p < 1) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_len = *(p++); - if (p + cookie_len > d + n) { + if ((unsigned int)((d + n ) - p) < cookie_len) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; @@ -1131,7 +1132,7 @@ int ssl3_get_client_hello(SSL *s) } } - if (p + 2 > d + n) { + if ((d + n ) - p < 2) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; @@ -1145,7 +1146,7 @@ int ssl3_get_client_hello(SSL *s) } /* i bytes of cipher data + 1 byte for compression length later */ - if ((p + i + 1) > (d + n)) { + if ((d + n) - p < i + 1) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); @@ -1211,7 +1212,7 @@ int ssl3_get_client_hello(SSL *s) /* compression */ i = *(p++); - if ((p + i) > (d + n)) { + if ((d + n) - p < i) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); @@ -1872,6 +1873,11 @@ int ssl3_send_server_key_exchange(SSL *s) goto f_err; } kn = EVP_PKEY_size(pkey); + /* Allow space for signature algorithm */ + if (SSL_USE_SIGALGS(s)) + kn += 2; + /* Allow space for signature length */ + kn += 2; } else { pkey = NULL; kn = 0; @@ -2229,11 +2235,8 @@ int ssl3_get_client_key_exchange(SSL *s) * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */ - /* - * should be RAND_bytes, but we cannot work around a failure. - */ - if (RAND_pseudo_bytes(rand_premaster_secret, - sizeof(rand_premaster_secret)) <= 0) + if (RAND_bytes(rand_premaster_secret, + sizeof(rand_premaster_secret)) <= 0) goto err; decrypt_len = RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING); @@ -2323,7 +2326,8 @@ int ssl3_get_client_key_exchange(SSL *s) if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG); - goto err; + al = SSL_AD_HANDSHAKE_FAILURE; + goto f_err; } else { p -= 2; i = (int)n; @@ -2376,9 +2380,10 @@ int ssl3_get_client_key_exchange(SSL *s) i = DH_compute_key(p, pub, dh_srvr); if (i <= 0) { + al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB); BN_clear_free(pub); - goto err; + goto f_err; } DH_free(s->s3->tmp.dh); @@ -2676,12 +2681,14 @@ int ssl3_get_client_key_exchange(SSL *s) i = *p; p += 1; if (n != 1 + i) { - SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); - goto err; + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH); + al = SSL_AD_DECODE_ERROR; + goto f_err; } if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); - goto err; + al = SSL_AD_HANDSHAKE_FAILURE; + goto f_err; } /* * p is pointing to somewhere in the buffer currently, so set it @@ -3213,6 +3220,12 @@ int ssl3_get_client_certificate(SSL *s) goto f_err; } for (nc = 0; nc < llen;) { + if (nc + 3 > llen) { + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, + SSL_R_CERT_LENGTH_MISMATCH); + goto f_err; + } n2l3(p, l); if ((l + nc + 3) > llen) { al = SSL_AD_DECODE_ERROR; @@ -3497,37 +3510,34 @@ int ssl3_send_cert_status(SSL *s) { if (s->state == SSL3_ST_SW_CERT_STATUS_A) { unsigned char *p; + size_t msglen; + /*- * Grow buffer if need be: the length calculation is as - * follows 1 (message type) + 3 (message length) + + * follows handshake_header_length + * 1 (ocsp response type) + 3 (ocsp response length) * + (ocsp response) */ - if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) { + msglen = 4 + s->tlsext_ocsp_resplen; + if (!BUF_MEM_grow(s->init_buf, SSL_HM_HEADER_LENGTH(s) + msglen)) { s->state = SSL_ST_ERR; return -1; } - p = (unsigned char *)s->init_buf->data; + p = ssl_handshake_start(s); - /* do the header */ - *(p++) = SSL3_MT_CERTIFICATE_STATUS; - /* message length */ - l2n3(s->tlsext_ocsp_resplen + 4, p); /* status type */ *(p++) = s->tlsext_status_type; /* length of OCSP response */ l2n3(s->tlsext_ocsp_resplen, p); /* actual response */ memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen); - /* number of bytes to write */ - s->init_num = 8 + s->tlsext_ocsp_resplen; - s->state = SSL3_ST_SW_CERT_STATUS_B; - s->init_off = 0; + + ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_STATUS, msglen); } /* SSL3_ST_SW_CERT_STATUS_B */ - return (ssl3_do_write(s, SSL3_RT_HANDSHAKE)); + return (ssl_do_write(s)); } # ifndef OPENSSL_NO_NEXTPROTONEG diff --git a/ssl/ssl.h b/ssl/ssl.h index 5ef56faa5099..90aeb0ce4e1e 100644 --- a/ssl/ssl.h +++ b/ssl/ssl.h @@ -2532,7 +2532,6 @@ void SSL_set_tmp_ecdh_callback(SSL *ssl, int keylength)); # endif -# ifndef OPENSSL_NO_COMP const COMP_METHOD *SSL_get_current_compression(SSL *s); const COMP_METHOD *SSL_get_current_expansion(SSL *s); const char *SSL_COMP_get_name(const COMP_METHOD *comp); @@ -2541,13 +2540,6 @@ STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP) *meths); void SSL_COMP_free_compression_methods(void); int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm); -# else -const void *SSL_get_current_compression(SSL *s); -const void *SSL_get_current_expansion(SSL *s); -const char *SSL_COMP_get_name(const void *comp); -void *SSL_COMP_get_compression_methods(void); -int SSL_COMP_add_compression_method(int id, void *cm); -# endif const SSL_CIPHER *SSL_CIPHER_find(SSL *ssl, const unsigned char *ptr); @@ -2623,6 +2615,7 @@ void ERR_load_SSL_strings(void); # define SSL_F_DTLS1_HEARTBEAT 305 # define SSL_F_DTLS1_OUTPUT_CERT_CHAIN 255 # define SSL_F_DTLS1_PREPROCESS_FRAGMENT 288 +# define SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS 424 # define SSL_F_DTLS1_PROCESS_OUT_OF_SEQ_MESSAGE 256 # define SSL_F_DTLS1_PROCESS_RECORD 257 # define SSL_F_DTLS1_READ_BYTES 258 @@ -3114,6 +3107,7 @@ void ERR_load_SSL_strings(void); # define SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST 157 # define SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST 233 # define SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG 234 +# define SSL_R_TOO_MANY_WARN_ALERTS 409 # define SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER 235 # define SSL_R_UNABLE_TO_DECODE_DH_CERTS 236 # define SSL_R_UNABLE_TO_DECODE_ECDH_CERTS 313 diff --git a/ssl/ssl_asn1.c b/ssl/ssl_asn1.c index 35cc27c5e985..499f0e85addf 100644 --- a/ssl/ssl_asn1.c +++ b/ssl/ssl_asn1.c @@ -527,6 +527,9 @@ SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp, if (os.length > SSL_MAX_SID_CTX_LENGTH) { c.error = SSL_R_BAD_LENGTH; c.line = __LINE__; + OPENSSL_free(os.data); + os.data = NULL; + os.length = 0; goto err; } else { ret->sid_ctx_length = os.length; diff --git a/ssl/ssl_ciph.c b/ssl/ssl_ciph.c index 302464e643ea..2ad8f4392236 100644 --- a/ssl/ssl_ciph.c +++ b/ssl/ssl_ciph.c @@ -1932,17 +1932,27 @@ SSL_COMP *ssl3_comp_find(STACK_OF(SSL_COMP) *sk, int n) } #ifdef OPENSSL_NO_COMP -void *SSL_COMP_get_compression_methods(void) +STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void) { return NULL; } -int SSL_COMP_add_compression_method(int id, void *cm) +STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP) + *meths) +{ + return NULL; +} + +void SSL_COMP_free_compression_methods(void) +{ +} + +int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm) { return 1; } -const char *SSL_COMP_get_name(const void *comp) +const char *SSL_COMP_get_name(const COMP_METHOD *comp) { return NULL; } @@ -1996,6 +2006,11 @@ int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm) MemCheck_off(); comp = (SSL_COMP *)OPENSSL_malloc(sizeof(SSL_COMP)); + if (comp == NULL) { + MemCheck_on(); + SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD, ERR_R_MALLOC_FAILURE); + return 1; + } comp->id = id; comp->method = cm; load_builtin_compressions(); diff --git a/ssl/ssl_err.c b/ssl/ssl_err.c index 704088dc469e..79aaf1a838b7 100644 --- a/ssl/ssl_err.c +++ b/ssl/ssl_err.c @@ -1,6 +1,6 @@ /* ssl/ssl_err.c */ /* ==================================================================== - * Copyright (c) 1999-2015 The OpenSSL Project. All rights reserved. + * Copyright (c) 1999-2016 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -93,6 +93,8 @@ static ERR_STRING_DATA SSL_str_functs[] = { {ERR_FUNC(SSL_F_DTLS1_HEARTBEAT), "dtls1_heartbeat"}, {ERR_FUNC(SSL_F_DTLS1_OUTPUT_CERT_CHAIN), "dtls1_output_cert_chain"}, {ERR_FUNC(SSL_F_DTLS1_PREPROCESS_FRAGMENT), "DTLS1_PREPROCESS_FRAGMENT"}, + {ERR_FUNC(SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS), + "DTLS1_PROCESS_BUFFERED_RECORDS"}, {ERR_FUNC(SSL_F_DTLS1_PROCESS_OUT_OF_SEQ_MESSAGE), "DTLS1_PROCESS_OUT_OF_SEQ_MESSAGE"}, {ERR_FUNC(SSL_F_DTLS1_PROCESS_RECORD), "DTLS1_PROCESS_RECORD"}, diff --git a/ssl/ssl_lib.c b/ssl/ssl_lib.c index fd94325bb3a4..42b980ac26a0 100644 --- a/ssl/ssl_lib.c +++ b/ssl/ssl_lib.c @@ -1828,7 +1828,7 @@ int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen, const unsigned char *p, size_t plen, int use_context) { - if (s->version < TLS1_VERSION) + if (s->version < TLS1_VERSION && s->version != DTLS1_BAD_VER) return -1; return s->method->ssl3_enc->export_keying_material(s, out, olen, label, @@ -2000,7 +2000,7 @@ SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth) ret->tlsext_servername_callback = 0; ret->tlsext_servername_arg = NULL; /* Setup RFC4507 ticket keys */ - if ((RAND_pseudo_bytes(ret->tlsext_tick_key_name, 16) <= 0) + if ((RAND_bytes(ret->tlsext_tick_key_name, 16) <= 0) || (RAND_bytes(ret->tlsext_tick_hmac_key, 16) <= 0) || (RAND_bytes(ret->tlsext_tick_aes_key, 16) <= 0)) ret->options |= SSL_OP_NO_TICKET; @@ -3050,12 +3050,12 @@ const SSL_CIPHER *SSL_get_current_cipher(const SSL *s) } #ifdef OPENSSL_NO_COMP -const void *SSL_get_current_compression(SSL *s) +const COMP_METHOD *SSL_get_current_compression(SSL *s) { return NULL; } -const void *SSL_get_current_expansion(SSL *s) +const COMP_METHOD *SSL_get_current_expansion(SSL *s) { return NULL; } diff --git a/ssl/ssl_locl.h b/ssl/ssl_locl.h index 747e718a52bf..6df725f7d73a 100644 --- a/ssl/ssl_locl.h +++ b/ssl/ssl_locl.h @@ -491,6 +491,12 @@ # define SSL_CLIENT_USE_TLS1_2_CIPHERS(s) \ ((SSL_IS_DTLS(s) && s->client_version <= DTLS1_2_VERSION) || \ (!SSL_IS_DTLS(s) && s->client_version >= TLS1_2_VERSION)) +/* + * Determine if a client should send signature algorithms extension: + * as with TLS1.2 cipher we can't rely on method flags. + */ +# define SSL_CLIENT_USE_SIGALGS(s) \ + SSL_CLIENT_USE_TLS1_2_CIPHERS(s) /* Mostly for SSLv3 */ # define SSL_PKEY_RSA_ENC 0 @@ -585,6 +591,8 @@ typedef struct { */ # define SSL_EXT_FLAG_SENT 0x2 +# define MAX_WARN_ALERT_COUNT 5 + typedef struct { custom_ext_method *meths; size_t meths_count; @@ -692,6 +700,8 @@ typedef struct cert_st { unsigned char *alpn_proposed; /* server */ unsigned int alpn_proposed_len; int alpn_sent; /* client */ + /* Count of the number of consecutive warning alerts received */ + unsigned int alert_count; } CERT; typedef struct sess_cert_st { @@ -1242,7 +1252,8 @@ int dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off, int *found); int dtls1_get_queue_priority(unsigned short seq, int is_ccs); int dtls1_retransmit_buffered_messages(SSL *s); -void dtls1_clear_record_buffer(SSL *s); +void dtls1_clear_received_buffer(SSL *s); +void dtls1_clear_sent_buffer(SSL *s); void dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr); void dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr); diff --git a/ssl/ssl_rsa.c b/ssl/ssl_rsa.c index 82022470bfd7..f679801a297c 100644 --- a/ssl/ssl_rsa.c +++ b/ssl/ssl_rsa.c @@ -912,6 +912,8 @@ static int serverinfo_process_buffer(const unsigned char *serverinfo, int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo, size_t serverinfo_length) { + unsigned char *new_serverinfo; + if (ctx == NULL || serverinfo == NULL || serverinfo_length == 0) { SSLerr(SSL_F_SSL_CTX_USE_SERVERINFO, ERR_R_PASSED_NULL_PARAMETER); return 0; @@ -928,12 +930,13 @@ int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo, SSLerr(SSL_F_SSL_CTX_USE_SERVERINFO, ERR_R_INTERNAL_ERROR); return 0; } - ctx->cert->key->serverinfo = OPENSSL_realloc(ctx->cert->key->serverinfo, - serverinfo_length); - if (ctx->cert->key->serverinfo == NULL) { + new_serverinfo = OPENSSL_realloc(ctx->cert->key->serverinfo, + serverinfo_length); + if (new_serverinfo == NULL) { SSLerr(SSL_F_SSL_CTX_USE_SERVERINFO, ERR_R_MALLOC_FAILURE); return 0; } + ctx->cert->key->serverinfo = new_serverinfo; memcpy(ctx->cert->key->serverinfo, serverinfo, serverinfo_length); ctx->cert->key->serverinfo_length = serverinfo_length; diff --git a/ssl/ssl_sess.c b/ssl/ssl_sess.c index b18299834384..ed9855f90cf8 100644 --- a/ssl/ssl_sess.c +++ b/ssl/ssl_sess.c @@ -382,7 +382,7 @@ static int def_generate_session_id(const SSL *ssl, unsigned char *id, { unsigned int retry = 0; do - if (RAND_pseudo_bytes(id, *id_len) <= 0) + if (RAND_bytes(id, *id_len) <= 0) return 0; while (SSL_has_matching_session_id(ssl, id, *id_len) && (++retry < MAX_SESS_ID_ATTEMPTS)) ; @@ -573,7 +573,7 @@ int ssl_get_prev_session(SSL *s, unsigned char *session_id, int len, int r; #endif - if (session_id + len > limit) { + if (limit - session_id < len) { fatal = 1; goto err; } @@ -919,6 +919,10 @@ int SSL_set_session(SSL *s, SSL_SESSION *session) session->krb5_client_princ_len > 0) { s->kssl_ctx->client_princ = (char *)OPENSSL_malloc(session->krb5_client_princ_len + 1); + if (s->kssl_ctx->client_princ == NULL) { + SSLerr(SSL_F_SSL_SET_SESSION, ERR_R_MALLOC_FAILURE); + return 0; + } memcpy(s->kssl_ctx->client_princ, session->krb5_client_princ, session->krb5_client_princ_len); s->kssl_ctx->client_princ[session->krb5_client_princ_len] = '\0'; @@ -1123,7 +1127,7 @@ int ssl_clear_bad_session(SSL *s) if ((s->session != NULL) && !(s->shutdown & SSL_SENT_SHUTDOWN) && !(SSL_in_init(s) || SSL_in_before(s))) { - SSL_CTX_remove_session(s->ctx, s->session); + SSL_CTX_remove_session(s->session_ctx, s->session); return (1); } else return (0); diff --git a/ssl/ssltest.c b/ssl/ssltest.c index 1db84ad5f9aa..890e47685350 100644 --- a/ssl/ssltest.c +++ b/ssl/ssltest.c @@ -3141,9 +3141,12 @@ static unsigned int psk_server_callback(SSL *ssl, const char *identity, static int do_test_cipherlist(void) { +#if !defined(OPENSSL_NO_SSL2) || !defined(OPENSSL_NO_SSL3) || \ + !defined(OPENSSL_NO_TLS1) int i = 0; const SSL_METHOD *meth; const SSL_CIPHER *ci, *tci = NULL; +#endif #ifndef OPENSSL_NO_SSL2 fprintf(stderr, "testing SSLv2 cipher list order: "); diff --git a/ssl/sslv2conftest.c b/ssl/sslv2conftest.c index 1fd748b11866..2aed9950b91d 100644 --- a/ssl/sslv2conftest.c +++ b/ssl/sslv2conftest.c @@ -84,7 +84,7 @@ int main(int argc, char *argv[]) { BIO *err; int testresult = 0; - int currtest; + int currtest = 0; SSL_library_init(); SSL_load_error_strings(); diff --git a/ssl/t1_enc.c b/ssl/t1_enc.c index 514fcb3e4e74..b6d1ee95a521 100644 --- a/ssl/t1_enc.c +++ b/ssl/t1_enc.c @@ -673,7 +673,6 @@ int tls1_setup_key_block(SSL *s) if ((p2 = (unsigned char *)OPENSSL_malloc(num)) == NULL) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE); - OPENSSL_free(p1); goto err; } #ifdef TLS_DEBUG diff --git a/ssl/t1_lib.c b/ssl/t1_lib.c index dd5bd0050d89..7831046b9261 100644 --- a/ssl/t1_lib.c +++ b/ssl/t1_lib.c @@ -1429,7 +1429,7 @@ unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, } skip_ext: - if (SSL_USE_SIGALGS(s)) { + if (SSL_CLIENT_USE_SIGALGS(s)) { size_t salglen; const unsigned char *salg; salglen = tls12_get_psigalgs(s, &salg); @@ -1867,11 +1867,11 @@ static void ssl_check_for_safari(SSL *s, const unsigned char *data, 0x02, 0x03, /* SHA-1/ECDSA */ }; - if (data >= (limit - 2)) + if (limit - data <= 2) return; data += 2; - if (data > (limit - 4)) + if (limit - data < 4) return; n2s(data, type); n2s(data, size); @@ -1879,7 +1879,7 @@ static void ssl_check_for_safari(SSL *s, const unsigned char *data, if (type != TLSEXT_TYPE_server_name) return; - if (data + size > limit) + if (limit - data < size) return; data += size; @@ -1887,7 +1887,7 @@ static void ssl_check_for_safari(SSL *s, const unsigned char *data, const size_t len1 = sizeof(kSafariExtensionsBlock); const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock); - if (data + len1 + len2 != limit) + if (limit - data != (int)(len1 + len2)) return; if (memcmp(data, kSafariExtensionsBlock, len1) != 0) return; @@ -1896,7 +1896,7 @@ static void ssl_check_for_safari(SSL *s, const unsigned char *data, } else { const size_t len = sizeof(kSafariExtensionsBlock); - if (data + len != limit) + if (limit - data != (int)(len)) return; if (memcmp(data, kSafariExtensionsBlock, len) != 0) return; @@ -2053,19 +2053,19 @@ static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, if (data == limit) goto ri_check; - if (data > (limit - 2)) + if (limit - data < 2) goto err; n2s(data, len); - if (data + len != limit) + if (limit - data != len) goto err; - while (data <= (limit - 4)) { + while (limit - data >= 4) { n2s(data, type); n2s(data, size); - if (data + size > (limit)) + if (limit - data < size) goto err; # if 0 fprintf(stderr, "Received extension type %d size %d\n", type, size); @@ -2316,6 +2316,23 @@ static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, size -= 2; if (dsize > size) goto err; + + /* + * We remove any OCSP_RESPIDs from a previous handshake + * to prevent unbounded memory growth - CVE-2016-6304 + */ + sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, + OCSP_RESPID_free); + if (dsize > 0) { + s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null(); + if (s->tlsext_ocsp_ids == NULL) { + *al = SSL_AD_INTERNAL_ERROR; + return 0; + } + } else { + s->tlsext_ocsp_ids = NULL; + } + while (dsize > 0) { OCSP_RESPID *id; int idsize; @@ -2335,13 +2352,6 @@ static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, OCSP_RESPID_free(id); goto err; } - if (!s->tlsext_ocsp_ids - && !(s->tlsext_ocsp_ids = - sk_OCSP_RESPID_new_null())) { - OCSP_RESPID_free(id); - *al = SSL_AD_INTERNAL_ERROR; - return 0; - } if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; @@ -2472,18 +2482,18 @@ static int ssl_scan_clienthello_custom_tlsext(SSL *s, if (s->hit || s->cert->srv_ext.meths_count == 0) return 1; - if (data >= limit - 2) + if (limit - data <= 2) return 1; n2s(data, len); - if (data > limit - len) + if (limit - data < len) return 1; - while (data <= limit - 4) { + while (limit - data >= 4) { n2s(data, type); n2s(data, size); - if (data + size > limit) + if (limit - data < size) return 1; if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0) return 0; @@ -2569,20 +2579,20 @@ static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif - if (data >= (d + n - 2)) + if ((d + n) - data <= 2) goto ri_check; n2s(data, length); - if (data + length != d + n) { + if ((d + n) - data != length) { *al = SSL_AD_DECODE_ERROR; return 0; } - while (data <= (d + n - 4)) { + while ((d + n) - data >= 4) { n2s(data, type); n2s(data, size); - if (data + size > (d + n)) + if ((d + n) - data < size) goto ri_check; if (s->tlsext_debug_cb) @@ -2712,6 +2722,11 @@ static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, *al = TLS1_AD_INTERNAL_ERROR; return 0; } + /* + * Could be non-NULL if server has sent multiple NPN extensions in + * a single Serverhello + */ + OPENSSL_free(s->next_proto_negotiated); s->next_proto_negotiated = OPENSSL_malloc(selected_len); if (!s->next_proto_negotiated) { *al = TLS1_AD_INTERNAL_ERROR; @@ -3307,29 +3322,33 @@ int tls1_process_ticket(SSL *s, unsigned char *session_id, int len, /* Skip past DTLS cookie */ if (SSL_IS_DTLS(s)) { i = *(p++); - p += i; - if (p >= limit) + + if (limit - p <= i) return -1; + + p += i; } /* Skip past cipher list */ n2s(p, i); - p += i; - if (p >= limit) + if (limit - p <= i) return -1; + p += i; + /* Skip past compression algorithm list */ i = *(p++); - p += i; - if (p > limit) + if (limit - p < i) return -1; + p += i; + /* Now at start of extensions */ - if ((p + 2) >= limit) + if (limit - p <= 2) return 0; n2s(p, i); - while ((p + 4) <= limit) { + while (limit - p >= 4) { unsigned short type, size; n2s(p, type); n2s(p, size); - if (p + size > limit) + if (limit - p < size) return 0; if (type == TLSEXT_TYPE_session_ticket) { int r; @@ -3397,9 +3416,7 @@ static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, HMAC_CTX hctx; EVP_CIPHER_CTX ctx; SSL_CTX *tctx = s->initial_ctx; - /* Need at least keyname + iv + some encrypted data */ - if (eticklen < 48) - return 2; + /* Initialize session ticket encryption and HMAC contexts */ HMAC_CTX_init(&hctx); EVP_CIPHER_CTX_init(&ctx); @@ -3433,6 +3450,13 @@ static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, if (mlen < 0) { goto err; } + /* Sanity check ticket length: must exceed keyname + IV + HMAC */ + if (eticklen <= 16 + EVP_CIPHER_CTX_iv_length(&ctx) + mlen) { + HMAC_CTX_cleanup(&hctx); + EVP_CIPHER_CTX_cleanup(&ctx); + return 2; + } + eticklen -= mlen; /* Check HMAC of encrypted ticket */ if (HMAC_Update(&hctx, etick, eticklen) <= 0 @@ -3902,7 +3926,7 @@ int tls1_process_heartbeat(SSL *s) memcpy(bp, pl, payload); bp += payload; /* Random padding */ - if (RAND_pseudo_bytes(bp, padding) < 0) { + if (RAND_bytes(bp, padding) <= 0) { OPENSSL_free(buffer); return -1; } @@ -3980,6 +4004,8 @@ int tls1_heartbeat(SSL *s) * - Padding */ buf = OPENSSL_malloc(1 + 2 + payload + padding); + if (buf == NULL) + return -1; p = buf; /* Message Type */ *p++ = TLS1_HB_REQUEST; @@ -3988,13 +4014,13 @@ int tls1_heartbeat(SSL *s) /* Sequence number */ s2n(s->tlsext_hb_seq, p); /* 16 random bytes */ - if (RAND_pseudo_bytes(p, 16) < 0) { + if (RAND_bytes(p, 16) <= 0) { SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR); goto err; } p += 16; /* Random padding */ - if (RAND_pseudo_bytes(p, padding) < 0) { + if (RAND_bytes(p, padding) <= 0) { SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR); goto err; } |