Home | History | Annotate | Line # | Download | only in test
regress_ssl.c revision 1.2.6.4
      1 /*	$NetBSD: regress_ssl.c,v 1.2.6.4 2017/05/04 06:04:03 snj Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      9  * 1. Redistributions of source code must retain the above copyright
     10  *    notice, this list of conditions and the following disclaimer.
     11  * 2. Redistributions in binary form must reproduce the above copyright
     12  *    notice, this list of conditions and the following disclaimer in the
     13  *    documentation and/or other materials provided with the distribution.
     14  * 3. The name of the author may not be used to endorse or promote products
     15  *    derived from this software without specific prior written permission.
     16  *
     17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 // Get rid of OSX 10.7 and greater deprecation warnings.
     30 #if defined(__APPLE__) && defined(__clang__)
     31 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
     32 #endif
     33 
     34 #ifdef _WIN32
     35 #include <winsock2.h>
     36 #include <windows.h>
     37 #endif
     38 
     39 #ifndef _WIN32
     40 #include <sys/types.h>
     41 #include <sys/socket.h>
     42 #include <netinet/in.h>
     43 #endif
     44 
     45 #include "event2/util.h"
     46 #include "event2/event.h"
     47 #include "event2/bufferevent_ssl.h"
     48 #include "event2/buffer.h"
     49 #include "event2/listener.h"
     50 
     51 #include "regress.h"
     52 #include "tinytest.h"
     53 #include "tinytest_macros.h"
     54 
     55 #include <openssl/asn1.h>
     56 #include <openssl/ssl.h>
     57 #include <openssl/bio.h>
     58 #include <openssl/crypto.h>
     59 #include <openssl/err.h>
     60 #include <openssl/pem.h>
     61 #include <openssl/opensslv.h>
     62 #include <openssl/x509.h>
     63 
     64 #include <string.h>
     65 
     66 #if OPENSSL_VERSION_NUMBER < 0x10100000L
     67 #define OpenSSL_version_num SSLeay
     68 #endif /* OPENSSL_VERSION_NUMBER */
     69 
     70 /* A short pre-generated key, to save the cost of doing an RSA key generation
     71  * step during the unit tests.  It's only 512 bits long, and it is published
     72  * in this file, so you would have to be very foolish to consider using it in
     73  * your own code. */
     74 static const char KEY[] =
     75     "-----BEGIN RSA PRIVATE KEY-----\n"
     76     "MIIBOgIBAAJBAKibTEzXjj+sqpipePX1lEk5BNFuL/dDBbw8QCXgaJWikOiKHeJq\n"
     77     "3FQ0OmCnmpkdsPFE4x3ojYmmdgE2i0dJwq0CAwEAAQJAZ08gpUS+qE1IClps/2gG\n"
     78     "AAer6Bc31K2AaiIQvCSQcH440cp062QtWMC3V5sEoWmdLsbAHFH26/9ZHn5zAflp\n"
     79     "gQIhANWOx/UYeR8HD0WREU5kcuSzgzNLwUErHLzxP7U6aojpAiEAyh2H35CjN/P7\n"
     80     "NhcZ4QYw3PeUWpqgJnaE/4i80BSYkSUCIQDLHFhLYLJZ80HwHTADif/ISn9/Ow6b\n"
     81     "p6BWh3DbMar/eQIgBPS6azH5vpp983KXkNv9AL4VZi9ac/b+BeINdzC6GP0CIDmB\n"
     82     "U6GFEQTZ3IfuiVabG5pummdC4DNbcdI+WKrSFNmQ\n"
     83     "-----END RSA PRIVATE KEY-----\n";
     84 
     85 static EVP_PKEY *
     86 getkey(void)
     87 {
     88 	EVP_PKEY *key;
     89 	BIO *bio;
     90 
     91 	/* new read-only BIO backed by KEY. */
     92 	bio = BIO_new_mem_buf((char*)KEY, -1);
     93 	tt_assert(bio);
     94 
     95 	key = PEM_read_bio_PrivateKey(bio,NULL,NULL,NULL);
     96 	BIO_free(bio);
     97 	tt_assert(key);
     98 
     99 	return key;
    100 end:
    101 	return NULL;
    102 }
    103 
    104 static X509 *
    105 getcert(void)
    106 {
    107 	/* Dummy code to make a quick-and-dirty valid certificate with
    108 	   OpenSSL.  Don't copy this code into your own program! It does a
    109 	   number of things in a stupid and insecure way. */
    110 	X509 *x509 = NULL;
    111 	X509_NAME *name = NULL;
    112 	EVP_PKEY *key = getkey();
    113 	int nid;
    114 	time_t now = time(NULL);
    115 
    116 	tt_assert(key);
    117 
    118 	x509 = X509_new();
    119 	tt_assert(x509);
    120 	tt_assert(0 != X509_set_version(x509, 2));
    121 	tt_assert(0 != ASN1_INTEGER_set(X509_get_serialNumber(x509),
    122 		(long)now));
    123 
    124 	name = X509_NAME_new();
    125 	tt_assert(name);
    126 	nid = OBJ_txt2nid("commonName");
    127 	tt_assert(NID_undef != nid);
    128 	tt_assert(0 != X509_NAME_add_entry_by_NID(
    129 		    name, nid, MBSTRING_ASC, (unsigned char*)"example.com",
    130 		    -1, -1, 0));
    131 
    132 	X509_set_subject_name(x509, name);
    133 	X509_set_issuer_name(x509, name);
    134 
    135 #if OPENSSL_VERSION_NUMBER < 0x10100000L
    136 	X509_time_adj(X509_get_notBefore(x509), 0, &now);
    137 	now += 3600;
    138 	X509_time_adj(X509_get_notAfter(x509), 0, &now);
    139 #else /* OPENSSL_VERSION_NUMBER >= 0x10100000L */
    140 	X509_time_adj(X509_getm_notBefore(x509), 0, &now);
    141 	now += 3600;
    142 	X509_time_adj(X509_getm_notAfter(x509), 0, &now);
    143 #endif /* OPENSSL_VERSION_NUMBER */
    144 	X509_set_pubkey(x509, key);
    145 	tt_assert(0 != X509_sign(x509, key, EVP_sha1()));
    146 
    147 	return x509;
    148 end:
    149 	X509_free(x509);
    150 	return NULL;
    151 }
    152 
    153 static int disable_tls_11_and_12 = 0;
    154 static SSL_CTX *the_ssl_ctx = NULL;
    155 
    156 static SSL_CTX *
    157 get_ssl_ctx(void)
    158 {
    159 	if (the_ssl_ctx)
    160 		return the_ssl_ctx;
    161 	the_ssl_ctx = SSL_CTX_new(SSLv23_method());
    162 	if (!the_ssl_ctx)
    163 		return NULL;
    164 	if (disable_tls_11_and_12) {
    165 #ifdef SSL_OP_NO_TLSv1_2
    166 		SSL_CTX_set_options(the_ssl_ctx, SSL_OP_NO_TLSv1_2);
    167 #endif
    168 #ifdef SSL_OP_NO_TLSv1_1
    169 		SSL_CTX_set_options(the_ssl_ctx, SSL_OP_NO_TLSv1_1);
    170 #endif
    171 	}
    172 	return the_ssl_ctx;
    173 }
    174 
    175 static void
    176 init_ssl(void)
    177 {
    178 	SSL_library_init();
    179 	ERR_load_crypto_strings();
    180 	SSL_load_error_strings();
    181 	OpenSSL_add_all_algorithms();
    182 	if (OpenSSL_version_num() != OPENSSL_VERSION_NUMBER) {
    183 		TT_DECLARE("WARN", ("Version mismatch for openssl: compiled with %lx but running with %lx", (unsigned long)OPENSSL_VERSION_NUMBER, (unsigned long) OpenSSL_version_num()));
    184 	}
    185 }
    186 
    187 /* ====================
    188    Here's a simple test: we read a number from the input, increment it, and
    189    reply, until we get to 1001.
    190 */
    191 
    192 static int test_is_done = 0;
    193 static int n_connected = 0;
    194 static int got_close = 0;
    195 static int got_error = 0;
    196 static int renegotiate_at = -1;
    197 static int stop_when_connected = 0;
    198 static int pending_connect_events = 0;
    199 static struct event_base *exit_base = NULL;
    200 
    201 static void
    202 respond_to_number(struct bufferevent *bev, void *ctx)
    203 {
    204 	struct evbuffer *b = bufferevent_get_input(bev);
    205 	char *line;
    206 	int n;
    207 	line = evbuffer_readln(b, NULL, EVBUFFER_EOL_LF);
    208 	if (! line)
    209 		return;
    210 	n = atoi(line);
    211 	if (n <= 0)
    212 		TT_FAIL(("Bad number: %s", line));
    213 	free(line);
    214 	TT_BLATHER(("The number was %d", n));
    215 	if (n == 1001) {
    216 		++test_is_done;
    217 		bufferevent_free(bev); /* Should trigger close on other side. */
    218 		return;
    219 	}
    220 	if (!strcmp(ctx, "client") && n == renegotiate_at) {
    221 		SSL_renegotiate(bufferevent_openssl_get_ssl(bev));
    222 	}
    223 	++n;
    224 	evbuffer_add_printf(bufferevent_get_output(bev),
    225 	    "%d\n", n);
    226 	TT_BLATHER(("Done reading; now writing."));
    227 	bufferevent_enable(bev, EV_WRITE);
    228 	bufferevent_disable(bev, EV_READ);
    229 }
    230 
    231 static void
    232 done_writing_cb(struct bufferevent *bev, void *ctx)
    233 {
    234 	struct evbuffer *b = bufferevent_get_output(bev);
    235 	if (evbuffer_get_length(b))
    236 		return;
    237 	TT_BLATHER(("Done writing."));
    238 	bufferevent_disable(bev, EV_WRITE);
    239 	bufferevent_enable(bev, EV_READ);
    240 }
    241 
    242 static void
    243 eventcb(struct bufferevent *bev, short what, void *ctx)
    244 {
    245 	TT_BLATHER(("Got event %d", (int)what));
    246 	if (what & BEV_EVENT_CONNECTED) {
    247 		SSL *ssl;
    248 		X509 *peer_cert;
    249 		++n_connected;
    250 		ssl = bufferevent_openssl_get_ssl(bev);
    251 		tt_assert(ssl);
    252 		peer_cert = SSL_get_peer_certificate(ssl);
    253 		if (0==strcmp(ctx, "server")) {
    254 			tt_assert(peer_cert == NULL);
    255 		} else {
    256 			tt_assert(peer_cert != NULL);
    257 		}
    258 		if (stop_when_connected) {
    259 			if (--pending_connect_events == 0)
    260 				event_base_loopexit(exit_base, NULL);
    261 		}
    262 	} else if (what & BEV_EVENT_EOF) {
    263 		TT_BLATHER(("Got a good EOF"));
    264 		++got_close;
    265 		bufferevent_free(bev);
    266 	} else if (what & BEV_EVENT_ERROR) {
    267 		TT_BLATHER(("Got an error."));
    268 		++got_error;
    269 		bufferevent_free(bev);
    270 	}
    271 end:
    272 	;
    273 }
    274 
    275 static void
    276 open_ssl_bufevs(struct bufferevent **bev1_out, struct bufferevent **bev2_out,
    277     struct event_base *base, int is_open, int flags, SSL *ssl1, SSL *ssl2,
    278     evutil_socket_t *fd_pair, struct bufferevent **underlying_pair)
    279 {
    280 	int state1 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_CONNECTING;
    281 	int state2 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_ACCEPTING;
    282 	if (fd_pair) {
    283 		*bev1_out = bufferevent_openssl_socket_new(
    284 			base, fd_pair[0], ssl1, state1, flags);
    285 		*bev2_out = bufferevent_openssl_socket_new(
    286 			base, fd_pair[1], ssl2, state2, flags);
    287 	} else {
    288 		*bev1_out = bufferevent_openssl_filter_new(
    289 			base, underlying_pair[0], ssl1, state1, flags);
    290 		*bev2_out = bufferevent_openssl_filter_new(
    291 			base, underlying_pair[1], ssl2, state2, flags);
    292 
    293 	}
    294 	bufferevent_setcb(*bev1_out, respond_to_number, done_writing_cb,
    295 	    eventcb, (void*)"client");
    296 	bufferevent_setcb(*bev2_out, respond_to_number, done_writing_cb,
    297 	    eventcb, (void*)"server");
    298 }
    299 
    300 static void
    301 regress_bufferevent_openssl(void *arg)
    302 {
    303 	struct basic_test_data *data = arg;
    304 
    305 	struct bufferevent *bev1, *bev2;
    306 	SSL *ssl1, *ssl2;
    307 	X509 *cert = getcert();
    308 	EVP_PKEY *key = getkey();
    309 	const int start_open = strstr((char*)data->setup_data, "open")!=NULL;
    310 	const int filter = strstr((char*)data->setup_data, "filter")!=NULL;
    311 	int flags = BEV_OPT_DEFER_CALLBACKS;
    312 	struct bufferevent *bev_ll[2] = { NULL, NULL };
    313 	evutil_socket_t *fd_pair = NULL;
    314 
    315 	tt_assert(cert);
    316 	tt_assert(key);
    317 
    318 	init_ssl();
    319 
    320 	if (strstr((char*)data->setup_data, "renegotiate")) {
    321 		if (OpenSSL_version_num() >= 0x10001000 &&
    322 		    OpenSSL_version_num() <  0x1000104f) {
    323 			/* 1.0.1 up to 1.0.1c has a bug where TLS1.1 and 1.2
    324 			 * can't renegotiate with themselves. Disable. */
    325 			disable_tls_11_and_12 = 1;
    326 		}
    327 		renegotiate_at = 600;
    328 	}
    329 
    330 	ssl1 = SSL_new(get_ssl_ctx());
    331 	ssl2 = SSL_new(get_ssl_ctx());
    332 
    333 	SSL_use_certificate(ssl2, cert);
    334 	SSL_use_PrivateKey(ssl2, key);
    335 
    336 	if (! start_open)
    337 		flags |= BEV_OPT_CLOSE_ON_FREE;
    338 
    339 	if (!filter) {
    340 		tt_assert(strstr((char*)data->setup_data, "socketpair"));
    341 		fd_pair = data->pair;
    342 	} else {
    343 		bev_ll[0] = bufferevent_socket_new(data->base, data->pair[0],
    344 		    BEV_OPT_CLOSE_ON_FREE);
    345 		bev_ll[1] = bufferevent_socket_new(data->base, data->pair[1],
    346 		    BEV_OPT_CLOSE_ON_FREE);
    347 	}
    348 
    349 	open_ssl_bufevs(&bev1, &bev2, data->base, 0, flags, ssl1, ssl2,
    350 	    fd_pair, bev_ll);
    351 
    352 	if (!filter) {
    353 		tt_int_op(bufferevent_getfd(bev1), ==, data->pair[0]);
    354 	} else {
    355 		tt_ptr_op(bufferevent_get_underlying(bev1), ==, bev_ll[0]);
    356 	}
    357 
    358 	if (start_open) {
    359 		pending_connect_events = 2;
    360 		stop_when_connected = 1;
    361 		exit_base = data->base;
    362 		event_base_dispatch(data->base);
    363 		/* Okay, now the renegotiation is done.  Make new
    364 		 * bufferevents to test opening in BUFFEREVENT_SSL_OPEN */
    365 		flags |= BEV_OPT_CLOSE_ON_FREE;
    366 		bufferevent_free(bev1);
    367 		bufferevent_free(bev2);
    368 		bev1 = bev2 = NULL;
    369 		open_ssl_bufevs(&bev1, &bev2, data->base, 1, flags, ssl1, ssl2,
    370 		    fd_pair, bev_ll);
    371 	}
    372 
    373 	bufferevent_enable(bev1, EV_READ|EV_WRITE);
    374 	bufferevent_enable(bev2, EV_READ|EV_WRITE);
    375 
    376 	evbuffer_add_printf(bufferevent_get_output(bev1), "1\n");
    377 
    378 	event_base_dispatch(data->base);
    379 
    380 	tt_assert(test_is_done == 1);
    381 	tt_assert(n_connected == 2);
    382 
    383 	/* We don't handle shutdown properly yet.
    384 	   tt_int_op(got_close, ==, 1);
    385 	   tt_int_op(got_error, ==, 0);
    386 	*/
    387 end:
    388 	return;
    389 }
    390 
    391 static void
    392 acceptcb(struct evconnlistener *listener, evutil_socket_t fd,
    393     struct sockaddr *addr, int socklen, void *arg)
    394 {
    395 	struct basic_test_data *data = arg;
    396 	struct bufferevent *bev;
    397 	SSL *ssl = SSL_new(get_ssl_ctx());
    398 
    399 	SSL_use_certificate(ssl, getcert());
    400 	SSL_use_PrivateKey(ssl, getkey());
    401 
    402 	bev = bufferevent_openssl_socket_new(
    403 		data->base,
    404 		fd,
    405 		ssl,
    406 		BUFFEREVENT_SSL_ACCEPTING,
    407 		BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
    408 
    409 	bufferevent_setcb(bev, respond_to_number, NULL, eventcb,
    410 	    (void*)"server");
    411 
    412 	bufferevent_enable(bev, EV_READ|EV_WRITE);
    413 
    414 	/* Only accept once, then disable ourself. */
    415 	evconnlistener_disable(listener);
    416 }
    417 
    418 static void
    419 regress_bufferevent_openssl_connect(void *arg)
    420 {
    421 	struct basic_test_data *data = arg;
    422 
    423 	struct event_base *base = data->base;
    424 
    425 	struct evconnlistener *listener;
    426 	struct bufferevent *bev;
    427 	struct sockaddr_in sin;
    428 	struct sockaddr_storage ss;
    429 	ev_socklen_t slen;
    430 
    431 	init_ssl();
    432 
    433 	memset(&sin, 0, sizeof(sin));
    434 	sin.sin_family = AF_INET;
    435 	sin.sin_addr.s_addr = htonl(0x7f000001);
    436 
    437 	memset(&ss, 0, sizeof(ss));
    438 	slen = sizeof(ss);
    439 
    440 	listener = evconnlistener_new_bind(base, acceptcb, data,
    441 	    LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
    442 	    -1, (struct sockaddr *)&sin, sizeof(sin));
    443 
    444 	tt_assert(listener);
    445 	tt_assert(evconnlistener_get_fd(listener) >= 0);
    446 
    447 	bev = bufferevent_openssl_socket_new(
    448 		data->base, -1, SSL_new(get_ssl_ctx()),
    449 		BUFFEREVENT_SSL_CONNECTING,
    450 		BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
    451 	tt_assert(bev);
    452 
    453 	bufferevent_setcb(bev, respond_to_number, NULL, eventcb,
    454 	    (void*)"client");
    455 
    456 	tt_assert(getsockname(evconnlistener_get_fd(listener),
    457 		(struct sockaddr*)&ss, &slen) == 0);
    458 	tt_assert(slen == sizeof(struct sockaddr_in));
    459 	tt_int_op(((struct sockaddr*)&ss)->sa_family, ==, AF_INET);
    460 	tt_int_op(((struct sockaddr*)&ss)->sa_family, ==, AF_INET);
    461 
    462 	tt_assert(0 ==
    463 	    bufferevent_socket_connect(bev, (struct sockaddr*)&ss, slen));
    464 	evbuffer_add_printf(bufferevent_get_output(bev), "1\n");
    465 	bufferevent_enable(bev, EV_READ|EV_WRITE);
    466 
    467 	event_base_dispatch(base);
    468 end:
    469 	;
    470 }
    471 
    472 struct testcase_t ssl_testcases[] = {
    473 
    474 	{ "bufferevent_socketpair", regress_bufferevent_openssl, TT_ISOLATED,
    475 	  &basic_setup, (void*)"socketpair" },
    476 	{ "bufferevent_filter", regress_bufferevent_openssl,
    477 	  TT_ISOLATED,
    478 	  &basic_setup, (void*)"filter" },
    479 	{ "bufferevent_renegotiate_socketpair", regress_bufferevent_openssl,
    480 	  TT_ISOLATED,
    481 	  &basic_setup, (void*)"socketpair renegotiate" },
    482 	{ "bufferevent_renegotiate_filter", regress_bufferevent_openssl,
    483 	  TT_ISOLATED,
    484 	  &basic_setup, (void*)"filter renegotiate" },
    485 	{ "bufferevent_socketpair_startopen", regress_bufferevent_openssl,
    486 	  TT_ISOLATED, &basic_setup, (void*)"socketpair open" },
    487 	{ "bufferevent_filter_startopen", regress_bufferevent_openssl,
    488 	  TT_ISOLATED, &basic_setup, (void*)"filter open" },
    489 
    490 	{ "bufferevent_connect", regress_bufferevent_openssl_connect,
    491 	  TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
    492 
    493 	END_OF_TESTCASES,
    494 };
    495