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