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