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