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