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