xref: /libevent-2.1.12/sample/https-client.c (revision f4489b83)
1 /*
2   This is an example of how to hook up evhttp with bufferevent_ssl
3 
4   It just GETs an https URL given on the command-line and prints the response
5   body to stdout.
6 
7   Actually, it also accepts plain http URLs to make it easy to compare http vs
8   https code paths.
9 
10   Loosely based on le-proxy.c.
11  */
12 
13 // Get rid of OSX 10.7 and greater deprecation warnings.
14 #if defined(__APPLE__) && defined(__clang__)
15 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
16 #endif
17 
18 #include <stdio.h>
19 #include <assert.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <errno.h>
23 
24 #ifdef _WIN32
25 #include <winsock2.h>
26 #include <ws2tcpip.h>
27 
28 #define snprintf _snprintf
29 #define strcasecmp _stricmp
30 #else
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #endif
34 
35 #include <event2/bufferevent_ssl.h>
36 #include <event2/bufferevent.h>
37 #include <event2/buffer.h>
38 #include <event2/listener.h>
39 #include <event2/util.h>
40 #include <event2/http.h>
41 
42 #include <openssl/ssl.h>
43 #include <openssl/err.h>
44 #include <openssl/rand.h>
45 
46 #include "openssl_hostname_validation.h"
47 
48 static struct event_base *base;
49 static int ignore_cert = 0;
50 
51 static void
52 http_request_done(struct evhttp_request *req, void *ctx)
53 {
54 	char buffer[256];
55 	int nread;
56 
57 	if (req == NULL) {
58 		/* If req is NULL, it means an error occurred, but
59 		 * sadly we are mostly left guessing what the error
60 		 * might have been.  We'll do our best... */
61 		struct bufferevent *bev = (struct bufferevent *) ctx;
62 		unsigned long oslerr;
63 		int printed_err = 0;
64 		int errcode = EVUTIL_SOCKET_ERROR();
65 		fprintf(stderr, "some request failed - no idea which one though!\n");
66 		/* Print out the OpenSSL error queue that libevent
67 		 * squirreled away for us, if any. */
68 		while ((oslerr = bufferevent_get_openssl_error(bev))) {
69 			ERR_error_string_n(oslerr, buffer, sizeof(buffer));
70 			fprintf(stderr, "%s\n", buffer);
71 			printed_err = 1;
72 		}
73 		/* If the OpenSSL error queue was empty, maybe it was a
74 		 * socket error; let's try printing that. */
75 		if (! printed_err)
76 			fprintf(stderr, "socket error = %s (%d)\n",
77 				evutil_socket_error_to_string(errcode),
78 				errcode);
79 		return;
80 	}
81 
82 	fprintf(stderr, "Response line: %d %s\n",
83 	    evhttp_request_get_response_code(req),
84 	    evhttp_request_get_response_code_line(req));
85 
86 	while ((nread = evbuffer_remove(evhttp_request_get_input_buffer(req),
87 		    buffer, sizeof(buffer)))
88 	       > 0) {
89 		/* These are just arbitrary chunks of 256 bytes.
90 		 * They are not lines, so we can't treat them as such. */
91 		fwrite(buffer, nread, 1, stdout);
92 	}
93 }
94 
95 static void
96 syntax(void)
97 {
98 	fputs("Syntax:\n", stderr);
99 	fputs("   https-client -url <https-url> [-data data-file.bin] [-ignore-cert] [-retries num] [-timeout sec] [-crt crt]\n", stderr);
100 	fputs("Example:\n", stderr);
101 	fputs("   https-client -url https://ip.appspot.com/\n", stderr);
102 }
103 
104 static void
105 err(const char *msg)
106 {
107 	fputs(msg, stderr);
108 }
109 
110 static void
111 err_openssl(const char *func)
112 {
113 	fprintf (stderr, "%s failed:\n", func);
114 
115 	/* This is the OpenSSL function that prints the contents of the
116 	 * error stack to the specified file handle. */
117 	ERR_print_errors_fp (stderr);
118 
119 	exit(1);
120 }
121 
122 /* See http://archives.seul.org/libevent/users/Jan-2013/msg00039.html */
123 static int cert_verify_callback(X509_STORE_CTX *x509_ctx, void *arg)
124 {
125 	char cert_str[256];
126 	const char *host = (const char *) arg;
127 	const char *res_str = "X509_verify_cert failed";
128 	HostnameValidationResult res = Error;
129 
130 	/* This is the function that OpenSSL would call if we hadn't called
131 	 * SSL_CTX_set_cert_verify_callback().  Therefore, we are "wrapping"
132 	 * the default functionality, rather than replacing it. */
133 	int ok_so_far = 0;
134 
135 	X509 *server_cert = NULL;
136 
137 	if (ignore_cert) {
138 		return 1;
139 	}
140 
141 	ok_so_far = X509_verify_cert(x509_ctx);
142 
143 	server_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
144 
145 	if (ok_so_far) {
146 		res = validate_hostname(host, server_cert);
147 
148 		switch (res) {
149 		case MatchFound:
150 			res_str = "MatchFound";
151 			break;
152 		case MatchNotFound:
153 			res_str = "MatchNotFound";
154 			break;
155 		case NoSANPresent:
156 			res_str = "NoSANPresent";
157 			break;
158 		case MalformedCertificate:
159 			res_str = "MalformedCertificate";
160 			break;
161 		case Error:
162 			res_str = "Error";
163 			break;
164 		default:
165 			res_str = "WTF!";
166 			break;
167 		}
168 	}
169 
170 	X509_NAME_oneline(X509_get_subject_name (server_cert),
171 			  cert_str, sizeof (cert_str));
172 
173 	if (res == MatchFound) {
174 		printf("https server '%s' has this certificate, "
175 		       "which looks good to me:\n%s\n",
176 		       host, cert_str);
177 		return 1;
178 	} else {
179 		printf("Got '%s' for hostname '%s' and certificate:\n%s\n",
180 		       res_str, host, cert_str);
181 		return 0;
182 	}
183 }
184 
185 int
186 main(int argc, char **argv)
187 {
188 	int r;
189 
190 	struct evhttp_uri *http_uri = NULL;
191 	const char *url = NULL, *data_file = NULL;
192 	const char *crt = "/etc/ssl/certs/ca-certificates.crt";
193 	const char *scheme, *host, *path, *query;
194 	char uri[256];
195 	int port;
196 	int retries = 0;
197 	int timeout = -1;
198 
199 	SSL_CTX *ssl_ctx = NULL;
200 	SSL *ssl = NULL;
201 	struct bufferevent *bev;
202 	struct evhttp_connection *evcon = NULL;
203 	struct evhttp_request *req;
204 	struct evkeyvalq *output_headers;
205 	struct evbuffer *output_buffer;
206 
207 	int i;
208 	int ret = 0;
209 	enum { HTTP, HTTPS } type = HTTP;
210 
211 	for (i = 1; i < argc; i++) {
212 		if (!strcmp("-url", argv[i])) {
213 			if (i < argc - 1) {
214 				url = argv[i + 1];
215 			} else {
216 				syntax();
217 				goto error;
218 			}
219 		} else if (!strcmp("-crt", argv[i])) {
220 			if (i < argc - 1) {
221 				crt = argv[i + 1];
222 			} else {
223 				syntax();
224 				goto error;
225 			}
226 		} else if (!strcmp("-ignore-cert", argv[i])) {
227 			ignore_cert = 1;
228 		} else if (!strcmp("-data", argv[i])) {
229 			if (i < argc - 1) {
230 				data_file = argv[i + 1];
231 			} else {
232 				syntax();
233 				goto error;
234 			}
235 		} else if (!strcmp("-retries", argv[i])) {
236 			if (i < argc - 1) {
237 				retries = atoi(argv[i + 1]);
238 			} else {
239 				syntax();
240 				goto error;
241 			}
242 		} else if (!strcmp("-timeout", argv[i])) {
243 			if (i < argc - 1) {
244 				timeout = atoi(argv[i + 1]);
245 			} else {
246 				syntax();
247 				goto error;
248 			}
249 		} else if (!strcmp("-help", argv[i])) {
250 			syntax();
251 			goto error;
252 		}
253 	}
254 
255 	if (!url) {
256 		syntax();
257 		goto error;
258 	}
259 
260 #ifdef _WIN32
261 	{
262 		WORD wVersionRequested;
263 		WSADATA wsaData;
264 		int err;
265 
266 		wVersionRequested = MAKEWORD(2, 2);
267 
268 		err = WSAStartup(wVersionRequested, &wsaData);
269 		if (err != 0) {
270 			printf("WSAStartup failed with error: %d\n", err);
271 			goto error;
272 		}
273 	}
274 #endif // _WIN32
275 
276 	http_uri = evhttp_uri_parse(url);
277 	if (http_uri == NULL) {
278 		err("malformed url");
279 		goto error;
280 	}
281 
282 	scheme = evhttp_uri_get_scheme(http_uri);
283 	if (scheme == NULL || (strcasecmp(scheme, "https") != 0 &&
284 	                       strcasecmp(scheme, "http") != 0)) {
285 		err("url must be http or https");
286 		goto error;
287 	}
288 
289 	host = evhttp_uri_get_host(http_uri);
290 	if (host == NULL) {
291 		err("url must have a host");
292 		goto error;
293 	}
294 
295 	port = evhttp_uri_get_port(http_uri);
296 	if (port == -1) {
297 		port = (strcasecmp(scheme, "http") == 0) ? 80 : 443;
298 	}
299 
300 	path = evhttp_uri_get_path(http_uri);
301 	if (strlen(path) == 0) {
302 		path = "/";
303 	}
304 
305 	query = evhttp_uri_get_query(http_uri);
306 	if (query == NULL) {
307 		snprintf(uri, sizeof(uri) - 1, "%s", path);
308 	} else {
309 		snprintf(uri, sizeof(uri) - 1, "%s?%s", path, query);
310 	}
311 	uri[sizeof(uri) - 1] = '\0';
312 
313 #if OPENSSL_VERSION_NUMBER < 0x10100000L
314 	// Initialize OpenSSL
315 	SSL_library_init();
316 	ERR_load_crypto_strings();
317 	SSL_load_error_strings();
318 	OpenSSL_add_all_algorithms();
319 #endif
320 
321 	/* This isn't strictly necessary... OpenSSL performs RAND_poll
322 	 * automatically on first use of random number generator. */
323 	r = RAND_poll();
324 	if (r == 0) {
325 		err_openssl("RAND_poll");
326 		goto error;
327 	}
328 
329 	/* Create a new OpenSSL context */
330 	ssl_ctx = SSL_CTX_new(SSLv23_method());
331 	if (!ssl_ctx) {
332 		err_openssl("SSL_CTX_new");
333 		goto error;
334 	}
335 
336 #ifndef _WIN32
337 	/* TODO: Add certificate loading on Windows as well */
338 
339 	/* Attempt to use the system's trusted root certificates.
340 	 * (This path is only valid for Debian-based systems.) */
341 	if (1 != SSL_CTX_load_verify_locations(ssl_ctx, crt, NULL)) {
342 		err_openssl("SSL_CTX_load_verify_locations");
343 		goto error;
344 	}
345 	/* Ask OpenSSL to verify the server certificate.  Note that this
346 	 * does NOT include verifying that the hostname is correct.
347 	 * So, by itself, this means anyone with any legitimate
348 	 * CA-issued certificate for any website, can impersonate any
349 	 * other website in the world.  This is not good.  See "The
350 	 * Most Dangerous Code in the World" article at
351 	 * https://crypto.stanford.edu/~dabo/pubs/abstracts/ssl-client-bugs.html
352 	 */
353 	SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
354 	/* This is how we solve the problem mentioned in the previous
355 	 * comment.  We "wrap" OpenSSL's validation routine in our
356 	 * own routine, which also validates the hostname by calling
357 	 * the code provided by iSECPartners.  Note that even though
358 	 * the "Everything You've Always Wanted to Know About
359 	 * Certificate Validation With OpenSSL (But Were Afraid to
360 	 * Ask)" paper from iSECPartners says very explicitly not to
361 	 * call SSL_CTX_set_cert_verify_callback (at the bottom of
362 	 * page 2), what we're doing here is safe because our
363 	 * cert_verify_callback() calls X509_verify_cert(), which is
364 	 * OpenSSL's built-in routine which would have been called if
365 	 * we hadn't set the callback.  Therefore, we're just
366 	 * "wrapping" OpenSSL's routine, not replacing it. */
367 	SSL_CTX_set_cert_verify_callback(ssl_ctx, cert_verify_callback,
368 					  (void *) host);
369 #endif // not _WIN32
370 
371 	// Create event base
372 	base = event_base_new();
373 	if (!base) {
374 		perror("event_base_new()");
375 		goto error;
376 	}
377 
378 	// Create OpenSSL bufferevent and stack evhttp on top of it
379 	ssl = SSL_new(ssl_ctx);
380 	if (ssl == NULL) {
381 		err_openssl("SSL_new()");
382 		goto error;
383 	}
384 
385 	#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
386 	// Set hostname for SNI extension
387 	SSL_set_tlsext_host_name(ssl, host);
388 	#endif
389 
390 	if (strcasecmp(scheme, "http") == 0) {
391 		bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
392 	} else {
393 		type = HTTPS;
394 		bev = bufferevent_openssl_socket_new(base, -1, ssl,
395 			BUFFEREVENT_SSL_CONNECTING,
396 			BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
397 	}
398 
399 	if (bev == NULL) {
400 		fprintf(stderr, "bufferevent_openssl_socket_new() failed\n");
401 		goto error;
402 	}
403 
404 	bufferevent_openssl_set_allow_dirty_shutdown(bev, 1);
405 
406 	// For simplicity, we let DNS resolution block. Everything else should be
407 	// asynchronous though.
408 	evcon = evhttp_connection_base_bufferevent_new(base, NULL, bev,
409 		host, port);
410 	if (evcon == NULL) {
411 		fprintf(stderr, "evhttp_connection_base_bufferevent_new() failed\n");
412 		goto error;
413 	}
414 
415 	if (retries > 0) {
416 		evhttp_connection_set_retries(evcon, retries);
417 	}
418 	if (timeout >= 0) {
419 		evhttp_connection_set_timeout(evcon, timeout);
420 	}
421 
422 	// Fire off the request
423 	req = evhttp_request_new(http_request_done, bev);
424 	if (req == NULL) {
425 		fprintf(stderr, "evhttp_request_new() failed\n");
426 		goto error;
427 	}
428 
429 	output_headers = evhttp_request_get_output_headers(req);
430 	evhttp_add_header(output_headers, "Host", host);
431 	evhttp_add_header(output_headers, "Connection", "close");
432 
433 	if (data_file) {
434 		/* NOTE: In production code, you'd probably want to use
435 		 * evbuffer_add_file() or evbuffer_add_file_segment(), to
436 		 * avoid needless copying. */
437 		FILE * f = fopen(data_file, "rb");
438 		char buf[1024];
439 		size_t s;
440 		size_t bytes = 0;
441 
442 		if (!f) {
443 			syntax();
444 			goto error;
445 		}
446 
447 		output_buffer = evhttp_request_get_output_buffer(req);
448 		while ((s = fread(buf, 1, sizeof(buf), f)) > 0) {
449 			evbuffer_add(output_buffer, buf, s);
450 			bytes += s;
451 		}
452 		evutil_snprintf(buf, sizeof(buf)-1, "%lu", (unsigned long)bytes);
453 		evhttp_add_header(output_headers, "Content-Length", buf);
454 		fclose(f);
455 	}
456 
457 	r = evhttp_make_request(evcon, req, data_file ? EVHTTP_REQ_POST : EVHTTP_REQ_GET, uri);
458 	if (r != 0) {
459 		fprintf(stderr, "evhttp_make_request() failed\n");
460 		goto error;
461 	}
462 
463 	event_base_dispatch(base);
464 	goto cleanup;
465 
466 error:
467 	ret = 1;
468 cleanup:
469 	if (evcon)
470 		evhttp_connection_free(evcon);
471 	if (http_uri)
472 		evhttp_uri_free(http_uri);
473 	event_base_free(base);
474 
475 	if (ssl_ctx)
476 		SSL_CTX_free(ssl_ctx);
477 	if (type == HTTP && ssl)
478 		SSL_free(ssl);
479 #if OPENSSL_VERSION_NUMBER < 0x10100000L
480 	EVP_cleanup();
481 	ERR_free_strings();
482 
483 #ifdef EVENT__HAVE_ERR_REMOVE_THREAD_STATE
484 	ERR_remove_thread_state(NULL);
485 #else
486 	ERR_remove_state(0);
487 #endif
488 	CRYPTO_cleanup_all_ex_data();
489 
490 	sk_SSL_COMP_free(SSL_COMP_get_compression_methods());
491 #endif /*OPENSSL_VERSION_NUMBER < 0x10100000L */
492 
493 #ifdef _WIN32
494 	WSACleanup();
495 #endif
496 
497 	return ret;
498 }
499