xref: /freebsd/contrib/ntp/sntp/libevent/test/regress_ssl.c (revision 63d1fd5970ec814904aa0f4580b10a0d302d08b2)
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 	free(line);
198 	TT_BLATHER(("The number was %d", n));
199 	if (n == 1001) {
200 		++test_is_done;
201 		bufferevent_free(bev); /* Should trigger close on other side. */
202 		return;
203 	}
204 	if (!strcmp(ctx, "client") && n == renegotiate_at) {
205 		SSL_renegotiate(bufferevent_openssl_get_ssl(bev));
206 	}
207 	++n;
208 	evbuffer_add_printf(bufferevent_get_output(bev),
209 	    "%d\n", n);
210 	TT_BLATHER(("Done reading; now writing."));
211 	bufferevent_enable(bev, EV_WRITE);
212 	bufferevent_disable(bev, EV_READ);
213 }
214 
215 static void
216 done_writing_cb(struct bufferevent *bev, void *ctx)
217 {
218 	struct evbuffer *b = bufferevent_get_output(bev);
219 	if (evbuffer_get_length(b))
220 		return;
221 	TT_BLATHER(("Done writing."));
222 	bufferevent_disable(bev, EV_WRITE);
223 	bufferevent_enable(bev, EV_READ);
224 }
225 
226 static void
227 eventcb(struct bufferevent *bev, short what, void *ctx)
228 {
229 	TT_BLATHER(("Got event %d", (int)what));
230 	if (what & BEV_EVENT_CONNECTED) {
231 		SSL *ssl;
232 		X509 *peer_cert;
233 		++n_connected;
234 		ssl = bufferevent_openssl_get_ssl(bev);
235 		tt_assert(ssl);
236 		peer_cert = SSL_get_peer_certificate(ssl);
237 		if (0==strcmp(ctx, "server")) {
238 			tt_assert(peer_cert == NULL);
239 		} else {
240 			tt_assert(peer_cert != NULL);
241 		}
242 		if (stop_when_connected) {
243 			if (--pending_connect_events == 0)
244 				event_base_loopexit(exit_base, NULL);
245 		}
246 	} else if (what & BEV_EVENT_EOF) {
247 		TT_BLATHER(("Got a good EOF"));
248 		++got_close;
249 		bufferevent_free(bev);
250 	} else if (what & BEV_EVENT_ERROR) {
251 		TT_BLATHER(("Got an error."));
252 		++got_error;
253 		bufferevent_free(bev);
254 	}
255 end:
256 	;
257 }
258 
259 static void
260 open_ssl_bufevs(struct bufferevent **bev1_out, struct bufferevent **bev2_out,
261     struct event_base *base, int is_open, int flags, SSL *ssl1, SSL *ssl2,
262     evutil_socket_t *fd_pair, struct bufferevent **underlying_pair)
263 {
264 	int state1 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_CONNECTING;
265 	int state2 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_ACCEPTING;
266 	if (fd_pair) {
267 		*bev1_out = bufferevent_openssl_socket_new(
268 			base, fd_pair[0], ssl1, state1, flags);
269 		*bev2_out = bufferevent_openssl_socket_new(
270 			base, fd_pair[1], ssl2, state2, flags);
271 	} else {
272 		*bev1_out = bufferevent_openssl_filter_new(
273 			base, underlying_pair[0], ssl1, state1, flags);
274 		*bev2_out = bufferevent_openssl_filter_new(
275 			base, underlying_pair[1], ssl2, state2, flags);
276 
277 	}
278 	bufferevent_setcb(*bev1_out, respond_to_number, done_writing_cb,
279 	    eventcb, (void*)"client");
280 	bufferevent_setcb(*bev2_out, respond_to_number, done_writing_cb,
281 	    eventcb, (void*)"server");
282 }
283 
284 static void
285 regress_bufferevent_openssl(void *arg)
286 {
287 	struct basic_test_data *data = arg;
288 
289 	struct bufferevent *bev1, *bev2;
290 	SSL *ssl1, *ssl2;
291 	X509 *cert = getcert();
292 	EVP_PKEY *key = getkey();
293 	const int start_open = strstr((char*)data->setup_data, "open")!=NULL;
294 	const int filter = strstr((char*)data->setup_data, "filter")!=NULL;
295 	int flags = BEV_OPT_DEFER_CALLBACKS;
296 	struct bufferevent *bev_ll[2] = { NULL, NULL };
297 	evutil_socket_t *fd_pair = NULL;
298 
299 	tt_assert(cert);
300 	tt_assert(key);
301 
302 	init_ssl();
303 
304 	if (strstr((char*)data->setup_data, "renegotiate")) {
305 		if (SSLeay() >= 0x10001000 &&
306 		    SSLeay() <  0x1000104f) {
307 			/* 1.0.1 up to 1.0.1c has a bug where TLS1.1 and 1.2
308 			 * can't renegotiate with themselves. Disable. */
309 			disable_tls_11_and_12 = 1;
310 		}
311 		renegotiate_at = 600;
312 	}
313 
314 	ssl1 = SSL_new(get_ssl_ctx());
315 	ssl2 = SSL_new(get_ssl_ctx());
316 
317 	SSL_use_certificate(ssl2, cert);
318 	SSL_use_PrivateKey(ssl2, key);
319 
320 	if (! start_open)
321 		flags |= BEV_OPT_CLOSE_ON_FREE;
322 
323 	if (!filter) {
324 		tt_assert(strstr((char*)data->setup_data, "socketpair"));
325 		fd_pair = data->pair;
326 	} else {
327 		bev_ll[0] = bufferevent_socket_new(data->base, data->pair[0],
328 		    BEV_OPT_CLOSE_ON_FREE);
329 		bev_ll[1] = bufferevent_socket_new(data->base, data->pair[1],
330 		    BEV_OPT_CLOSE_ON_FREE);
331 	}
332 
333 	open_ssl_bufevs(&bev1, &bev2, data->base, 0, flags, ssl1, ssl2,
334 	    fd_pair, bev_ll);
335 
336 	if (!filter) {
337 		tt_int_op(bufferevent_getfd(bev1), ==, data->pair[0]);
338 	} else {
339 		tt_ptr_op(bufferevent_get_underlying(bev1), ==, bev_ll[0]);
340 	}
341 
342 	if (start_open) {
343 		pending_connect_events = 2;
344 		stop_when_connected = 1;
345 		exit_base = data->base;
346 		event_base_dispatch(data->base);
347 		/* Okay, now the renegotiation is done.  Make new
348 		 * bufferevents to test opening in BUFFEREVENT_SSL_OPEN */
349 		flags |= BEV_OPT_CLOSE_ON_FREE;
350 		bufferevent_free(bev1);
351 		bufferevent_free(bev2);
352 		bev1 = bev2 = NULL;
353 		open_ssl_bufevs(&bev1, &bev2, data->base, 1, flags, ssl1, ssl2,
354 		    fd_pair, bev_ll);
355 	}
356 
357 	bufferevent_enable(bev1, EV_READ|EV_WRITE);
358 	bufferevent_enable(bev2, EV_READ|EV_WRITE);
359 
360 	evbuffer_add_printf(bufferevent_get_output(bev1), "1\n");
361 
362 	event_base_dispatch(data->base);
363 
364 	tt_assert(test_is_done == 1);
365 	tt_assert(n_connected == 2);
366 
367 	/* We don't handle shutdown properly yet.
368 	   tt_int_op(got_close, ==, 1);
369 	   tt_int_op(got_error, ==, 0);
370 	*/
371 end:
372 	return;
373 }
374 
375 static void
376 acceptcb(struct evconnlistener *listener, evutil_socket_t fd,
377     struct sockaddr *addr, int socklen, void *arg)
378 {
379 	struct basic_test_data *data = arg;
380 	struct bufferevent *bev;
381 	SSL *ssl = SSL_new(get_ssl_ctx());
382 
383 	SSL_use_certificate(ssl, getcert());
384 	SSL_use_PrivateKey(ssl, getkey());
385 
386 	bev = bufferevent_openssl_socket_new(
387 		data->base,
388 		fd,
389 		ssl,
390 		BUFFEREVENT_SSL_ACCEPTING,
391 		BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
392 
393 	bufferevent_setcb(bev, respond_to_number, NULL, eventcb,
394 	    (void*)"server");
395 
396 	bufferevent_enable(bev, EV_READ|EV_WRITE);
397 
398 	/* Only accept once, then disable ourself. */
399 	evconnlistener_disable(listener);
400 }
401 
402 static void
403 regress_bufferevent_openssl_connect(void *arg)
404 {
405 	struct basic_test_data *data = arg;
406 
407 	struct event_base *base = data->base;
408 
409 	struct evconnlistener *listener;
410 	struct bufferevent *bev;
411 	struct sockaddr_in sin;
412 	struct sockaddr_storage ss;
413 	ev_socklen_t slen;
414 
415 	init_ssl();
416 
417 	memset(&sin, 0, sizeof(sin));
418 	sin.sin_family = AF_INET;
419 	sin.sin_addr.s_addr = htonl(0x7f000001);
420 
421 	memset(&ss, 0, sizeof(ss));
422 	slen = sizeof(ss);
423 
424 	listener = evconnlistener_new_bind(base, acceptcb, data,
425 	    LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
426 	    -1, (struct sockaddr *)&sin, sizeof(sin));
427 
428 	tt_assert(listener);
429 	tt_assert(evconnlistener_get_fd(listener) >= 0);
430 
431 	bev = bufferevent_openssl_socket_new(
432 		data->base, -1, SSL_new(get_ssl_ctx()),
433 		BUFFEREVENT_SSL_CONNECTING,
434 		BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
435 	tt_assert(bev);
436 
437 	bufferevent_setcb(bev, respond_to_number, NULL, eventcb,
438 	    (void*)"client");
439 
440 	tt_assert(getsockname(evconnlistener_get_fd(listener),
441 		(struct sockaddr*)&ss, &slen) == 0);
442 	tt_assert(slen == sizeof(struct sockaddr_in));
443 	tt_int_op(((struct sockaddr*)&ss)->sa_family, ==, AF_INET);
444 	tt_int_op(((struct sockaddr*)&ss)->sa_family, ==, AF_INET);
445 
446 	tt_assert(0 ==
447 	    bufferevent_socket_connect(bev, (struct sockaddr*)&ss, slen));
448 	evbuffer_add_printf(bufferevent_get_output(bev), "1\n");
449 	bufferevent_enable(bev, EV_READ|EV_WRITE);
450 
451 	event_base_dispatch(base);
452 end:
453 	;
454 }
455 
456 struct testcase_t ssl_testcases[] = {
457 
458 	{ "bufferevent_socketpair", regress_bufferevent_openssl, TT_ISOLATED,
459 	  &basic_setup, (void*)"socketpair" },
460 	{ "bufferevent_filter", regress_bufferevent_openssl,
461 	  TT_ISOLATED,
462 	  &basic_setup, (void*)"filter" },
463 	{ "bufferevent_renegotiate_socketpair", regress_bufferevent_openssl,
464 	  TT_ISOLATED,
465 	  &basic_setup, (void*)"socketpair renegotiate" },
466 	{ "bufferevent_renegotiate_filter", regress_bufferevent_openssl,
467 	  TT_ISOLATED,
468 	  &basic_setup, (void*)"filter renegotiate" },
469 	{ "bufferevent_socketpair_startopen", regress_bufferevent_openssl,
470 	  TT_ISOLATED, &basic_setup, (void*)"socketpair open" },
471 	{ "bufferevent_filter_startopen", regress_bufferevent_openssl,
472 	  TT_ISOLATED, &basic_setup, (void*)"filter open" },
473 
474 	{ "bufferevent_connect", regress_bufferevent_openssl_connect,
475 	  TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
476 
477 	END_OF_TESTCASES,
478 };
479