xref: /libevent-2.1.12/sample/https-client.c (revision 24a1f25a)
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]\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 *scheme, *host, *path, *query;
193 	char uri[256];
194 	int port;
195 	int retries = 0;
196 
197 	SSL_CTX *ssl_ctx = NULL;
198 	SSL *ssl;
199 	struct bufferevent *bev;
200 	struct evhttp_connection *evcon = NULL;
201 	struct evhttp_request *req;
202 	struct evkeyvalq *output_headers;
203 	struct evbuffer *output_buffer;
204 
205 	int i;
206 	int ret = 0;
207 	enum { HTTP, HTTPS } type = HTTP;
208 
209 	for (i = 1; i < argc; i++) {
210 		if (!strcmp("-url", argv[i])) {
211 			if (i < argc - 1) {
212 				url = argv[i + 1];
213 			} else {
214 				syntax();
215 				goto error;
216 			}
217 		} else if (!strcmp("-ignore-cert", argv[i])) {
218 			ignore_cert = 1;
219 		} else if (!strcmp("-data", argv[i])) {
220 			if (i < argc - 1) {
221 				data_file = argv[i + 1];
222 			} else {
223 				syntax();
224 				goto error;
225 			}
226 		} else if (!strcmp("-retries", argv[i])) {
227 			if (i < argc - 1) {
228 				retries = atoi(argv[i + 1]);
229 			} else {
230 				syntax();
231 				goto error;
232 			}
233 		} else if (!strcmp("-help", argv[i])) {
234 			syntax();
235 			goto error;
236 		}
237 	}
238 
239 	if (!url) {
240 		syntax();
241 		goto error;
242 	}
243 
244 #ifdef _WIN32
245 	{
246 		WORD wVersionRequested;
247 		WSADATA wsaData;
248 		int err;
249 
250 		wVersionRequested = MAKEWORD(2, 2);
251 
252 		err = WSAStartup(wVersionRequested, &wsaData);
253 		if (err != 0) {
254 			printf("WSAStartup failed with error: %d\n", err);
255 			goto error;
256 		}
257 	}
258 #endif // _WIN32
259 
260 	http_uri = evhttp_uri_parse(url);
261 	if (http_uri == NULL) {
262 		err("malformed url");
263 		goto error;
264 	}
265 
266 	scheme = evhttp_uri_get_scheme(http_uri);
267 	if (scheme == NULL || (strcasecmp(scheme, "https") != 0 &&
268 	                       strcasecmp(scheme, "http") != 0)) {
269 		err("url must be http or https");
270 		goto error;
271 	}
272 
273 	host = evhttp_uri_get_host(http_uri);
274 	if (host == NULL) {
275 		err("url must have a host");
276 		goto error;
277 	}
278 
279 	port = evhttp_uri_get_port(http_uri);
280 	if (port == -1) {
281 		port = (strcasecmp(scheme, "http") == 0) ? 80 : 443;
282 	}
283 
284 	path = evhttp_uri_get_path(http_uri);
285 	if (strlen(path) == 0) {
286 		path = "/";
287 	}
288 
289 	query = evhttp_uri_get_query(http_uri);
290 	if (query == NULL) {
291 		snprintf(uri, sizeof(uri) - 1, "%s", path);
292 	} else {
293 		snprintf(uri, sizeof(uri) - 1, "%s?%s", path, query);
294 	}
295 	uri[sizeof(uri) - 1] = '\0';
296 
297 	// Initialize OpenSSL
298 	SSL_library_init();
299 	ERR_load_crypto_strings();
300 	SSL_load_error_strings();
301 	OpenSSL_add_all_algorithms();
302 
303 	/* This isn't strictly necessary... OpenSSL performs RAND_poll
304 	 * automatically on first use of random number generator. */
305 	r = RAND_poll();
306 	if (r == 0) {
307 		err_openssl("RAND_poll");
308 		goto error;
309 	}
310 
311 	/* Create a new OpenSSL context */
312 	ssl_ctx = SSL_CTX_new(SSLv23_method());
313 	if (!ssl_ctx) {
314 		err_openssl("SSL_CTX_new");
315 		goto error;
316 	}
317 
318 #ifndef _WIN32
319 	/* TODO: Add certificate loading on Windows as well */
320 
321 	/* Attempt to use the system's trusted root certificates.
322 	 * (This path is only valid for Debian-based systems.) */
323 	if (1 != SSL_CTX_load_verify_locations(ssl_ctx,
324 					       "/etc/ssl/certs/ca-certificates.crt",
325 					       NULL)) {
326 		err_openssl("SSL_CTX_load_verify_locations");
327 		goto error;
328 	}
329 	/* Ask OpenSSL to verify the server certificate.  Note that this
330 	 * does NOT include verifying that the hostname is correct.
331 	 * So, by itself, this means anyone with any legitimate
332 	 * CA-issued certificate for any website, can impersonate any
333 	 * other website in the world.  This is not good.  See "The
334 	 * Most Dangerous Code in the World" article at
335 	 * https://crypto.stanford.edu/~dabo/pubs/abstracts/ssl-client-bugs.html
336 	 */
337 	SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
338 	/* This is how we solve the problem mentioned in the previous
339 	 * comment.  We "wrap" OpenSSL's validation routine in our
340 	 * own routine, which also validates the hostname by calling
341 	 * the code provided by iSECPartners.  Note that even though
342 	 * the "Everything You've Always Wanted to Know About
343 	 * Certificate Validation With OpenSSL (But Were Afraid to
344 	 * Ask)" paper from iSECPartners says very explicitly not to
345 	 * call SSL_CTX_set_cert_verify_callback (at the bottom of
346 	 * page 2), what we're doing here is safe because our
347 	 * cert_verify_callback() calls X509_verify_cert(), which is
348 	 * OpenSSL's built-in routine which would have been called if
349 	 * we hadn't set the callback.  Therefore, we're just
350 	 * "wrapping" OpenSSL's routine, not replacing it. */
351 	SSL_CTX_set_cert_verify_callback(ssl_ctx, cert_verify_callback,
352 					  (void *) host);
353 #endif // not _WIN32
354 
355 	// Create event base
356 	base = event_base_new();
357 	if (!base) {
358 		perror("event_base_new()");
359 		goto error;
360 	}
361 
362 	// Create OpenSSL bufferevent and stack evhttp on top of it
363 	ssl = SSL_new(ssl_ctx);
364 	if (ssl == NULL) {
365 		err_openssl("SSL_new()");
366 		goto error;
367 	}
368 
369 	#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
370 	// Set hostname for SNI extension
371 	SSL_set_tlsext_host_name(ssl, host);
372 	#endif
373 
374 	if (strcasecmp(scheme, "http") == 0) {
375 		bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
376 	} else {
377 		type = HTTPS;
378 		bev = bufferevent_openssl_socket_new(base, -1, ssl,
379 			BUFFEREVENT_SSL_CONNECTING,
380 			BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
381 	}
382 
383 	if (bev == NULL) {
384 		fprintf(stderr, "bufferevent_openssl_socket_new() failed\n");
385 		goto error;
386 	}
387 
388 	bufferevent_openssl_set_allow_dirty_shutdown(bev, 1);
389 
390 	// For simplicity, we let DNS resolution block. Everything else should be
391 	// asynchronous though.
392 	evcon = evhttp_connection_base_bufferevent_new(base, NULL, bev,
393 		host, port);
394 	if (evcon == NULL) {
395 		fprintf(stderr, "evhttp_connection_base_bufferevent_new() failed\n");
396 		goto error;
397 	}
398 
399 	if (retries > 0) {
400 		evhttp_connection_set_retries(evcon, retries);
401 	}
402 
403 	// Fire off the request
404 	req = evhttp_request_new(http_request_done, bev);
405 	if (req == NULL) {
406 		fprintf(stderr, "evhttp_request_new() failed\n");
407 		goto error;
408 	}
409 
410 	output_headers = evhttp_request_get_output_headers(req);
411 	evhttp_add_header(output_headers, "Host", host);
412 	evhttp_add_header(output_headers, "Connection", "close");
413 
414 	if (data_file) {
415 		/* NOTE: In production code, you'd probably want to use
416 		 * evbuffer_add_file() or evbuffer_add_file_segment(), to
417 		 * avoid needless copying. */
418 		FILE * f = fopen(data_file, "rb");
419 		char buf[1024];
420 		size_t s;
421 		size_t bytes = 0;
422 
423 		if (!f) {
424 			syntax();
425 			goto error;
426 		}
427 
428 		output_buffer = evhttp_request_get_output_buffer(req);
429 		while ((s = fread(buf, 1, sizeof(buf), f)) > 0) {
430 			evbuffer_add(output_buffer, buf, s);
431 			bytes += s;
432 		}
433 		evutil_snprintf(buf, sizeof(buf)-1, "%lu", (unsigned long)bytes);
434 		evhttp_add_header(output_headers, "Content-Length", buf);
435 		fclose(f);
436 	}
437 
438 	r = evhttp_make_request(evcon, req, data_file ? EVHTTP_REQ_POST : EVHTTP_REQ_GET, uri);
439 	if (r != 0) {
440 		fprintf(stderr, "evhttp_make_request() failed\n");
441 		goto error;
442 	}
443 
444 	event_base_dispatch(base);
445 	goto cleanup;
446 
447 error:
448 	ret = 1;
449 cleanup:
450 	if (evcon)
451 		evhttp_connection_free(evcon);
452 	if (http_uri)
453 		evhttp_uri_free(http_uri);
454 	event_base_free(base);
455 
456 	if (ssl_ctx)
457 		SSL_CTX_free(ssl_ctx);
458 	if (type == HTTP)
459 		SSL_free(ssl);
460 	EVP_cleanup();
461 	ERR_free_strings();
462 
463 	ERR_remove_state(0);
464 	CRYPTO_cleanup_all_ex_data();
465 
466 	sk_SSL_COMP_free(SSL_COMP_get_compression_methods());
467 
468 #ifdef _WIN32
469 	WSACleanup();
470 #endif
471 
472 	return ret;
473 }
474