xref: /freebsd/contrib/ntp/sntp/libevent/test/regress_ssl.c (revision 788ca347b816afd83b2885e0c79aeeb88649b2ab)
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/ssl.h>
54 #include <openssl/bio.h>
55 #include <openssl/err.h>
56 #include <openssl/pem.h>
57 
58 #include <string.h>
59 
60 /* A short pre-generated key, to save the cost of doing an RSA key generation
61  * step during the unit tests.  It's only 512 bits long, and it is published
62  * in this file, so you would have to be very foolish to consider using it in
63  * your own code. */
64 static const char KEY[] =
65     "-----BEGIN RSA PRIVATE KEY-----\n"
66     "MIIBOgIBAAJBAKibTEzXjj+sqpipePX1lEk5BNFuL/dDBbw8QCXgaJWikOiKHeJq\n"
67     "3FQ0OmCnmpkdsPFE4x3ojYmmdgE2i0dJwq0CAwEAAQJAZ08gpUS+qE1IClps/2gG\n"
68     "AAer6Bc31K2AaiIQvCSQcH440cp062QtWMC3V5sEoWmdLsbAHFH26/9ZHn5zAflp\n"
69     "gQIhANWOx/UYeR8HD0WREU5kcuSzgzNLwUErHLzxP7U6aojpAiEAyh2H35CjN/P7\n"
70     "NhcZ4QYw3PeUWpqgJnaE/4i80BSYkSUCIQDLHFhLYLJZ80HwHTADif/ISn9/Ow6b\n"
71     "p6BWh3DbMar/eQIgBPS6azH5vpp983KXkNv9AL4VZi9ac/b+BeINdzC6GP0CIDmB\n"
72     "U6GFEQTZ3IfuiVabG5pummdC4DNbcdI+WKrSFNmQ\n"
73     "-----END RSA PRIVATE KEY-----\n";
74 
75 static EVP_PKEY *
76 getkey(void)
77 {
78 	EVP_PKEY *key;
79 	BIO *bio;
80 
81 	/* new read-only BIO backed by KEY. */
82 	bio = BIO_new_mem_buf((char*)KEY, -1);
83 	tt_assert(bio);
84 
85 	key = PEM_read_bio_PrivateKey(bio,NULL,NULL,NULL);
86 	BIO_free(bio);
87 	tt_assert(key);
88 
89 	return key;
90 end:
91 	return NULL;
92 }
93 
94 static X509 *
95 getcert(void)
96 {
97 	/* Dummy code to make a quick-and-dirty valid certificate with
98 	   OpenSSL.  Don't copy this code into your own program! It does a
99 	   number of things in a stupid and insecure way. */
100 	X509 *x509 = NULL;
101 	X509_NAME *name = NULL;
102 	EVP_PKEY *key = getkey();
103 	int nid;
104 	time_t now = time(NULL);
105 
106 	tt_assert(key);
107 
108 	x509 = X509_new();
109 	tt_assert(x509);
110 	tt_assert(0 != X509_set_version(x509, 2));
111 	tt_assert(0 != ASN1_INTEGER_set(X509_get_serialNumber(x509),
112 		(long)now));
113 
114 	name = X509_NAME_new();
115 	tt_assert(name);
116 	nid = OBJ_txt2nid("commonName");
117 	tt_assert(NID_undef != nid);
118 	tt_assert(0 != X509_NAME_add_entry_by_NID(
119 		    name, nid, MBSTRING_ASC, (unsigned char*)"example.com",
120 		    -1, -1, 0));
121 
122 	X509_set_subject_name(x509, name);
123 	X509_set_issuer_name(x509, name);
124 
125 	X509_time_adj(X509_get_notBefore(x509), 0, &now);
126 	now += 3600;
127 	X509_time_adj(X509_get_notAfter(x509), 0, &now);
128 	X509_set_pubkey(x509, key);
129 	tt_assert(0 != X509_sign(x509, key, EVP_sha1()));
130 
131 	return x509;
132 end:
133 	X509_free(x509);
134 	return NULL;
135 }
136 
137 static int disable_tls_11_and_12 = 0;
138 static SSL_CTX *the_ssl_ctx = NULL;
139 
140 static SSL_CTX *
141 get_ssl_ctx(void)
142 {
143 	if (the_ssl_ctx)
144 		return the_ssl_ctx;
145 	the_ssl_ctx = SSL_CTX_new(SSLv23_method());
146 	if (!the_ssl_ctx)
147 		return NULL;
148 	if (disable_tls_11_and_12) {
149 #ifdef SSL_OP_NO_TLSv1_2
150 		SSL_CTX_set_options(the_ssl_ctx, SSL_OP_NO_TLSv1_2);
151 #endif
152 #ifdef SSL_OP_NO_TLSv1_1
153 		SSL_CTX_set_options(the_ssl_ctx, SSL_OP_NO_TLSv1_1);
154 #endif
155 	}
156 	return the_ssl_ctx;
157 }
158 
159 static void
160 init_ssl(void)
161 {
162 	SSL_library_init();
163 	ERR_load_crypto_strings();
164 	SSL_load_error_strings();
165 	OpenSSL_add_all_algorithms();
166 	if (SSLeay() != OPENSSL_VERSION_NUMBER) {
167 		TT_DECLARE("WARN", ("Version mismatch for openssl: compiled with %lx but running with %lx", (unsigned long)OPENSSL_VERSION_NUMBER, (unsigned long) SSLeay()));
168 	}
169 }
170 
171 /* ====================
172    Here's a simple test: we read a number from the input, increment it, and
173    reply, until we get to 1001.
174 */
175 
176 static int test_is_done = 0;
177 static int n_connected = 0;
178 static int got_close = 0;
179 static int got_error = 0;
180 static int renegotiate_at = -1;
181 static int stop_when_connected = 0;
182 static int pending_connect_events = 0;
183 static struct event_base *exit_base = NULL;
184 
185 static void
186 respond_to_number(struct bufferevent *bev, void *ctx)
187 {
188 	struct evbuffer *b = bufferevent_get_input(bev);
189 	char *line;
190 	int n;
191 	line = evbuffer_readln(b, NULL, EVBUFFER_EOL_LF);
192 	if (! line)
193 		return;
194 	n = atoi(line);
195 	if (n <= 0)
196 		TT_FAIL(("Bad number: %s", line));
197 	TT_BLATHER(("The number was %d", n));
198 	if (n == 1001) {
199 		++test_is_done;
200 		bufferevent_free(bev); /* Should trigger close on other side. */
201 		return;
202 	}
203 	if (!strcmp(ctx, "client") && n == renegotiate_at) {
204 		SSL_renegotiate(bufferevent_openssl_get_ssl(bev));
205 	}
206 	++n;
207 	evbuffer_add_printf(bufferevent_get_output(bev),
208 	    "%d\n", n);
209 	TT_BLATHER(("Done reading; now writing."));
210 	bufferevent_enable(bev, EV_WRITE);
211 	bufferevent_disable(bev, EV_READ);
212 }
213 
214 static void
215 done_writing_cb(struct bufferevent *bev, void *ctx)
216 {
217 	struct evbuffer *b = bufferevent_get_output(bev);
218 	if (evbuffer_get_length(b))
219 		return;
220 	TT_BLATHER(("Done writing."));
221 	bufferevent_disable(bev, EV_WRITE);
222 	bufferevent_enable(bev, EV_READ);
223 }
224 
225 static void
226 eventcb(struct bufferevent *bev, short what, void *ctx)
227 {
228 	TT_BLATHER(("Got event %d", (int)what));
229 	if (what & BEV_EVENT_CONNECTED) {
230 		SSL *ssl;
231 		X509 *peer_cert;
232 		++n_connected;
233 		ssl = bufferevent_openssl_get_ssl(bev);
234 		tt_assert(ssl);
235 		peer_cert = SSL_get_peer_certificate(ssl);
236 		if (0==strcmp(ctx, "server")) {
237 			tt_assert(peer_cert == NULL);
238 		} else {
239 			tt_assert(peer_cert != NULL);
240 		}
241 		if (stop_when_connected) {
242 			if (--pending_connect_events == 0)
243 				event_base_loopexit(exit_base, NULL);
244 		}
245 	} else if (what & BEV_EVENT_EOF) {
246 		TT_BLATHER(("Got a good EOF"));
247 		++got_close;
248 		bufferevent_free(bev);
249 	} else if (what & BEV_EVENT_ERROR) {
250 		TT_BLATHER(("Got an error."));
251 		++got_error;
252 		bufferevent_free(bev);
253 	}
254 end:
255 	;
256 }
257 
258 static void
259 open_ssl_bufevs(struct bufferevent **bev1_out, struct bufferevent **bev2_out,
260     struct event_base *base, int is_open, int flags, SSL *ssl1, SSL *ssl2,
261     evutil_socket_t *fd_pair, struct bufferevent **underlying_pair)
262 {
263 	int state1 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_CONNECTING;
264 	int state2 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_ACCEPTING;
265 	if (fd_pair) {
266 		*bev1_out = bufferevent_openssl_socket_new(
267 			base, fd_pair[0], ssl1, state1, flags);
268 		*bev2_out = bufferevent_openssl_socket_new(
269 			base, fd_pair[1], ssl2, state2, flags);
270 	} else {
271 		*bev1_out = bufferevent_openssl_filter_new(
272 			base, underlying_pair[0], ssl1, state1, flags);
273 		*bev2_out = bufferevent_openssl_filter_new(
274 			base, underlying_pair[1], ssl2, state2, flags);
275 
276 	}
277 	bufferevent_setcb(*bev1_out, respond_to_number, done_writing_cb,
278 	    eventcb, (void*)"client");
279 	bufferevent_setcb(*bev2_out, respond_to_number, done_writing_cb,
280 	    eventcb, (void*)"server");
281 }
282 
283 static void
284 regress_bufferevent_openssl(void *arg)
285 {
286 	struct basic_test_data *data = arg;
287 
288 	struct bufferevent *bev1, *bev2;
289 	SSL *ssl1, *ssl2;
290 	X509 *cert = getcert();
291 	EVP_PKEY *key = getkey();
292 	const int start_open = strstr((char*)data->setup_data, "open")!=NULL;
293 	const int filter = strstr((char*)data->setup_data, "filter")!=NULL;
294 	int flags = BEV_OPT_DEFER_CALLBACKS;
295 	struct bufferevent *bev_ll[2] = { NULL, NULL };
296 	evutil_socket_t *fd_pair = NULL;
297 
298 	tt_assert(cert);
299 	tt_assert(key);
300 
301 	init_ssl();
302 
303 	if (strstr((char*)data->setup_data, "renegotiate")) {
304 		if (SSLeay() >= 0x10001000 &&
305 		    SSLeay() <  0x1000104f) {
306 			/* 1.0.1 up to 1.0.1c has a bug where TLS1.1 and 1.2
307 			 * can't renegotiate with themselves. Disable. */
308 			disable_tls_11_and_12 = 1;
309 		}
310 		renegotiate_at = 600;
311 	}
312 
313 	ssl1 = SSL_new(get_ssl_ctx());
314 	ssl2 = SSL_new(get_ssl_ctx());
315 
316 	SSL_use_certificate(ssl2, cert);
317 	SSL_use_PrivateKey(ssl2, key);
318 
319 	if (! start_open)
320 		flags |= BEV_OPT_CLOSE_ON_FREE;
321 
322 	if (!filter) {
323 		tt_assert(strstr((char*)data->setup_data, "socketpair"));
324 		fd_pair = data->pair;
325 	} else {
326 		bev_ll[0] = bufferevent_socket_new(data->base, data->pair[0],
327 		    BEV_OPT_CLOSE_ON_FREE);
328 		bev_ll[1] = bufferevent_socket_new(data->base, data->pair[1],
329 		    BEV_OPT_CLOSE_ON_FREE);
330 	}
331 
332 	open_ssl_bufevs(&bev1, &bev2, data->base, 0, flags, ssl1, ssl2,
333 	    fd_pair, bev_ll);
334 
335 	if (!filter) {
336 		tt_int_op(bufferevent_getfd(bev1), ==, data->pair[0]);
337 	} else {
338 		tt_ptr_op(bufferevent_get_underlying(bev1), ==, bev_ll[0]);
339 	}
340 
341 	if (start_open) {
342 		pending_connect_events = 2;
343 		stop_when_connected = 1;
344 		exit_base = data->base;
345 		event_base_dispatch(data->base);
346 		/* Okay, now the renegotiation is done.  Make new
347 		 * bufferevents to test opening in BUFFEREVENT_SSL_OPEN */
348 		flags |= BEV_OPT_CLOSE_ON_FREE;
349 		bufferevent_free(bev1);
350 		bufferevent_free(bev2);
351 		bev1 = bev2 = NULL;
352 		open_ssl_bufevs(&bev1, &bev2, data->base, 1, flags, ssl1, ssl2,
353 		    fd_pair, bev_ll);
354 	}
355 
356 	bufferevent_enable(bev1, EV_READ|EV_WRITE);
357 	bufferevent_enable(bev2, EV_READ|EV_WRITE);
358 
359 	evbuffer_add_printf(bufferevent_get_output(bev1), "1\n");
360 
361 	event_base_dispatch(data->base);
362 
363 	tt_assert(test_is_done == 1);
364 	tt_assert(n_connected == 2);
365 
366 	/* We don't handle shutdown properly yet.
367 	   tt_int_op(got_close, ==, 1);
368 	   tt_int_op(got_error, ==, 0);
369 	*/
370 end:
371 	return;
372 }
373 
374 static void
375 acceptcb(struct evconnlistener *listener, evutil_socket_t fd,
376     struct sockaddr *addr, int socklen, void *arg)
377 {
378 	struct basic_test_data *data = arg;
379 	struct bufferevent *bev;
380 	SSL *ssl = SSL_new(get_ssl_ctx());
381 
382 	SSL_use_certificate(ssl, getcert());
383 	SSL_use_PrivateKey(ssl, getkey());
384 
385 	bev = bufferevent_openssl_socket_new(
386 		data->base,
387 		fd,
388 		ssl,
389 		BUFFEREVENT_SSL_ACCEPTING,
390 		BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
391 
392 	bufferevent_setcb(bev, respond_to_number, NULL, eventcb,
393 	    (void*)"server");
394 
395 	bufferevent_enable(bev, EV_READ|EV_WRITE);
396 
397 	/* Only accept once, then disable ourself. */
398 	evconnlistener_disable(listener);
399 }
400 
401 static void
402 regress_bufferevent_openssl_connect(void *arg)
403 {
404 	struct basic_test_data *data = arg;
405 
406 	struct event_base *base = data->base;
407 
408 	struct evconnlistener *listener;
409 	struct bufferevent *bev;
410 	struct sockaddr_in sin;
411 	struct sockaddr_storage ss;
412 	ev_socklen_t slen;
413 
414 	init_ssl();
415 
416 	memset(&sin, 0, sizeof(sin));
417 	sin.sin_family = AF_INET;
418 	sin.sin_addr.s_addr = htonl(0x7f000001);
419 
420 	memset(&ss, 0, sizeof(ss));
421 	slen = sizeof(ss);
422 
423 	listener = evconnlistener_new_bind(base, acceptcb, data,
424 	    LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
425 	    -1, (struct sockaddr *)&sin, sizeof(sin));
426 
427 	tt_assert(listener);
428 	tt_assert(evconnlistener_get_fd(listener) >= 0);
429 
430 	bev = bufferevent_openssl_socket_new(
431 		data->base, -1, SSL_new(get_ssl_ctx()),
432 		BUFFEREVENT_SSL_CONNECTING,
433 		BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
434 	tt_assert(bev);
435 
436 	bufferevent_setcb(bev, respond_to_number, NULL, eventcb,
437 	    (void*)"client");
438 
439 	tt_assert(getsockname(evconnlistener_get_fd(listener),
440 		(struct sockaddr*)&ss, &slen) == 0);
441 	tt_assert(slen == sizeof(struct sockaddr_in));
442 	tt_int_op(((struct sockaddr*)&ss)->sa_family, ==, AF_INET);
443 	tt_int_op(((struct sockaddr*)&ss)->sa_family, ==, AF_INET);
444 
445 	tt_assert(0 ==
446 	    bufferevent_socket_connect(bev, (struct sockaddr*)&ss, slen));
447 	evbuffer_add_printf(bufferevent_get_output(bev), "1\n");
448 	bufferevent_enable(bev, EV_READ|EV_WRITE);
449 
450 	event_base_dispatch(base);
451 end:
452 	;
453 }
454 
455 struct testcase_t ssl_testcases[] = {
456 
457 	{ "bufferevent_socketpair", regress_bufferevent_openssl, TT_ISOLATED,
458 	  &basic_setup, (void*)"socketpair" },
459 	{ "bufferevent_filter", regress_bufferevent_openssl,
460 	  TT_ISOLATED,
461 	  &basic_setup, (void*)"filter" },
462 	{ "bufferevent_renegotiate_socketpair", regress_bufferevent_openssl,
463 	  TT_ISOLATED,
464 	  &basic_setup, (void*)"socketpair renegotiate" },
465 	{ "bufferevent_renegotiate_filter", regress_bufferevent_openssl,
466 	  TT_ISOLATED,
467 	  &basic_setup, (void*)"filter renegotiate" },
468 	{ "bufferevent_socketpair_startopen", regress_bufferevent_openssl,
469 	  TT_ISOLATED, &basic_setup, (void*)"socketpair open" },
470 	{ "bufferevent_filter_startopen", regress_bufferevent_openssl,
471 	  TT_ISOLATED, &basic_setup, (void*)"filter open" },
472 
473 	{ "bufferevent_connect", regress_bufferevent_openssl_connect,
474 	  TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
475 
476 	END_OF_TESTCASES,
477 };
478