xref: /libevent-2.1.12/sample/https-client.c (revision 8697b99c)
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 #ifdef __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 
50 static void
51 http_request_done(struct evhttp_request *req, void *ctx)
52 {
53 	char buffer[256];
54 	int nread;
55 
56 	if (req == NULL) {
57 		/* If req is NULL, it means an error occurred, but
58 		 * sadly we are mostly left guessing what the error
59 		 * might have been.  We'll do our best... */
60 		struct bufferevent *bev = (struct bufferevent *) ctx;
61 		unsigned long oslerr;
62 		int printed_err = 0;
63 		int errcode = EVUTIL_SOCKET_ERROR();
64 		fprintf(stderr, "some request failed - no idea which one though!\n");
65 		/* Print out the OpenSSL error queue that libevent
66 		 * squirreled away for us, if any. */
67 		while ((oslerr = bufferevent_get_openssl_error(bev))) {
68 			ERR_error_string_n(oslerr, buffer, sizeof(buffer));
69 			fprintf(stderr, "%s\n", buffer);
70 			printed_err = 1;
71 		}
72 		/* If the OpenSSL error queue was empty, maybe it was a
73 		 * socket error; let's try printing that. */
74 		if (! printed_err)
75 			fprintf(stderr, "socket error = %s (%d)\n",
76 				evutil_socket_error_to_string(errcode),
77 				errcode);
78 		return;
79 	}
80 
81 	fprintf(stderr, "Response line: %d %s\n",
82 	    evhttp_request_get_response_code(req),
83 	    evhttp_request_get_response_code_line(req));
84 
85 	while ((nread = evbuffer_remove(evhttp_request_get_input_buffer(req),
86 		    buffer, sizeof(buffer)))
87 	       > 0) {
88 		/* These are just arbitrary chunks of 256 bytes.
89 		 * They are not lines, so we can't treat them as such. */
90 		fwrite(buffer, nread, 1, stdout);
91 	}
92 }
93 
94 static void
95 syntax(void)
96 {
97 	fputs("Syntax:\n", stderr);
98 	fputs("   https-client <https-url>\n", stderr);
99 	fputs("Example:\n", stderr);
100 	fputs("   https-client https://ip.appspot.com/\n", stderr);
101 
102 	exit(1);
103 }
104 
105 static void
106 die(const char *msg)
107 {
108 	fputs(msg, stderr);
109 	exit(1);
110 }
111 
112 static void
113 die_openssl(const char *func)
114 {
115 	fprintf (stderr, "%s failed:\n", func);
116 
117 	/* This is the OpenSSL function that prints the contents of the
118 	 * error stack to the specified file handle. */
119 	ERR_print_errors_fp (stderr);
120 
121 	exit(1);
122 }
123 
124 /* See http://archives.seul.org/libevent/users/Jan-2013/msg00039.html */
125 static int cert_verify_callback(X509_STORE_CTX *x509_ctx, void *arg)
126 {
127 	char cert_str[256];
128 	const char *host = (const char *) arg;
129 	const char *res_str = "X509_verify_cert failed";
130 	HostnameValidationResult res = Error;
131 
132 	/* This is the function that OpenSSL would call if we hadn't called
133 	 * SSL_CTX_set_cert_verify_callback().  Therefore, we are "wrapping"
134 	 * the default functionality, rather than replacing it. */
135 	int ok_so_far = X509_verify_cert(x509_ctx);
136 
137 	X509 *server_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
138 
139 	if (ok_so_far) {
140 		res = validate_hostname(host, server_cert);
141 
142 		switch (res) {
143 		case MatchFound:
144 			res_str = "MatchFound";
145 			break;
146 		case MatchNotFound:
147 			res_str = "MatchNotFound";
148 			break;
149 		case NoSANPresent:
150 			res_str = "NoSANPresent";
151 			break;
152 		case MalformedCertificate:
153 			res_str = "MalformedCertificate";
154 			break;
155 		case Error:
156 			res_str = "Error";
157 			break;
158 		default:
159 			res_str = "WTF!";
160 			break;
161 		}
162 	}
163 
164 	X509_NAME_oneline(X509_get_subject_name (server_cert),
165 			  cert_str, sizeof (cert_str));
166 
167 	if (res == MatchFound) {
168 		printf("https server '%s' has this certificate, "
169 		       "which looks good to me:\n%s\n",
170 		       host, cert_str);
171 		return 1;
172 	} else {
173 		printf("Got '%s' for hostname '%s' and certificate:\n%s\n",
174 		       res_str, host, cert_str);
175 		return 0;
176 	}
177 }
178 
179 int
180 main(int argc, char **argv)
181 {
182 	int r;
183 
184 	struct evhttp_uri *http_uri;
185 	const char *url, *scheme, *host, *path, *query;
186 	char uri[256];
187 	int port;
188 
189 	SSL_CTX *ssl_ctx;
190 	SSL *ssl;
191 	struct bufferevent *bev;
192 	struct evhttp_connection *evcon;
193 	struct evhttp_request *req;
194 	struct evkeyvalq *output_headers;
195 
196 	if (argc != 2)
197 		syntax();
198 
199 #ifdef WIN32
200 	{
201 		WORD wVersionRequested;
202 		WSADATA wsaData;
203 		int err;
204 
205 		wVersionRequested = MAKEWORD(2, 2);
206 
207 		err = WSAStartup(wVersionRequested, &wsaData);
208 		if (err != 0) {
209 			printf("WSAStartup failed with error: %d\n", err);
210 			return 1;
211 		}
212 	}
213 #endif
214 
215 	url = argv[1];
216 	http_uri = evhttp_uri_parse(url);
217 	if (http_uri == NULL) {
218 		die("malformed url");
219 	}
220 
221 	scheme = evhttp_uri_get_scheme(http_uri);
222 	if (scheme == NULL || (strcasecmp(scheme, "https") != 0 &&
223 	                       strcasecmp(scheme, "http") != 0)) {
224 		die("url must be http or https");
225 	}
226 
227 	host = evhttp_uri_get_host(http_uri);
228 	if (host == NULL) {
229 		die("url must have a host");
230 	}
231 
232 	port = evhttp_uri_get_port(http_uri);
233 	if (port == -1) {
234 		port = (strcasecmp(scheme, "http") == 0) ? 80 : 443;
235 	}
236 
237 	path = evhttp_uri_get_path(http_uri);
238 	if (path == NULL) {
239 		path = "/";
240 	}
241 
242 	query = evhttp_uri_get_query(http_uri);
243 	if (query == NULL) {
244 		snprintf(uri, sizeof(uri) - 1, "%s", path);
245 	} else {
246 		snprintf(uri, sizeof(uri) - 1, "%s?%s", path, query);
247 	}
248 	uri[sizeof(uri) - 1] = '\0';
249 
250 	// Initialize OpenSSL
251 	SSL_library_init();
252 	ERR_load_crypto_strings();
253 	SSL_load_error_strings();
254 	OpenSSL_add_all_algorithms();
255 
256 	/* This isn't strictly necessary... OpenSSL performs RAND_poll
257 	 * automatically on first use of random number generator. */
258 	r = RAND_poll();
259 	if (r == 0) {
260 		die_openssl("RAND_poll");
261 	}
262 
263 	/* Create a new OpenSSL context */
264 	ssl_ctx = SSL_CTX_new(SSLv23_method());
265 	if (!ssl_ctx)
266 		die_openssl("SSL_CTX_new");
267 
268 	#ifndef WIN32
269 	/* TODO: Add certificate loading on Windows as well */
270 
271 	/* Attempt to use the system's trusted root certificates.
272 	 * (This path is only valid for Debian-based systems.) */
273 	if (1 != SSL_CTX_load_verify_locations(ssl_ctx,
274 					       "/etc/ssl/certs/ca-certificates.crt",
275 					       NULL))
276 		die_openssl("SSL_CTX_load_verify_locations");
277 	/* Ask OpenSSL to verify the server certificate.  Note that this
278 	 * does NOT include verifying that the hostname is correct.
279 	 * So, by itself, this means anyone with any legitimate
280 	 * CA-issued certificate for any website, can impersonate any
281 	 * other website in the world.  This is not good.  See "The
282 	 * Most Dangerous Code in the World" article at
283 	 * https://crypto.stanford.edu/~dabo/pubs/abstracts/ssl-client-bugs.html
284 	 */
285 	SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
286 	/* This is how we solve the problem mentioned in the previous
287 	 * comment.  We "wrap" OpenSSL's validation routine in our
288 	 * own routine, which also validates the hostname by calling
289 	 * the code provided by iSECPartners.  Note that even though
290 	 * the "Everything You've Always Wanted to Know About
291 	 * Certificate Validation With OpenSSL (But Were Afraid to
292 	 * Ask)" paper from iSECPartners says very explicitly not to
293 	 * call SSL_CTX_set_cert_verify_callback (at the bottom of
294 	 * page 2), what we're doing here is safe because our
295 	 * cert_verify_callback() calls X509_verify_cert(), which is
296 	 * OpenSSL's built-in routine which would have been called if
297 	 * we hadn't set the callback.  Therefore, we're just
298 	 * "wrapping" OpenSSL's routine, not replacing it. */
299 	SSL_CTX_set_cert_verify_callback (ssl_ctx, cert_verify_callback,
300 					  (void *) host);
301 	#endif // not WIN32
302 
303 	// Create event base
304 	base = event_base_new();
305 	if (!base) {
306 		perror("event_base_new()");
307 		return 1;
308 	}
309 
310 	// Create OpenSSL bufferevent and stack evhttp on top of it
311 	ssl = SSL_new(ssl_ctx);
312 	if (ssl == NULL) {
313 		die_openssl("SSL_new()");
314 	}
315 
316 	if (strcasecmp(scheme, "http") == 0) {
317 		bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
318 	} else {
319 		bev = bufferevent_openssl_socket_new(base, -1, ssl,
320 			BUFFEREVENT_SSL_CONNECTING,
321 			BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
322 	}
323 
324 	if (bev == NULL) {
325 		fprintf(stderr, "bufferevent_openssl_socket_new() failed\n");
326 		return 1;
327 	}
328 
329 	bufferevent_openssl_set_allow_dirty_shutdown(bev, 1);
330 
331 	// For simplicity, we let DNS resolution block. Everything else should be
332 	// asynchronous though.
333 	evcon = evhttp_connection_base_bufferevent_new(base, NULL, bev,
334 		host, port);
335 	if (evcon == NULL) {
336 		fprintf(stderr, "evhttp_connection_base_bufferevent_new() failed\n");
337 		return 1;
338 	}
339 
340 	// Fire off the request
341 	req = evhttp_request_new(http_request_done, bev);
342 	if (req == NULL) {
343 		fprintf(stderr, "evhttp_request_new() failed\n");
344 		return 1;
345 	}
346 
347 	output_headers = evhttp_request_get_output_headers(req);
348 	evhttp_add_header(output_headers, "Host", host);
349 	evhttp_add_header(output_headers, "Connection", "close");
350 
351 	r = evhttp_make_request(evcon, req, EVHTTP_REQ_GET, uri);
352 	if (r != 0) {
353 		fprintf(stderr, "evhttp_make_request() failed\n");
354 		return 1;
355 	}
356 
357 	event_base_dispatch(base);
358 
359 	evhttp_connection_free(evcon);
360 	event_base_free(base);
361 
362 #ifdef WIN32
363 	WSACleanup();
364 #endif
365 
366 	return 0;
367 }
368