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