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(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 struct evkeyvalq *output_headers; 186 187 if (argc != 2) 188 syntax(); 189 190 url = argv[1]; 191 http_uri = evhttp_uri_parse(url); 192 if (http_uri == NULL) { 193 die("malformed url"); 194 } 195 196 scheme = evhttp_uri_get_scheme(http_uri); 197 if (scheme == NULL || (strcasecmp(scheme, "https") != 0 && 198 strcasecmp(scheme, "http") != 0)) { 199 die("url must be http or https"); 200 } 201 202 host = evhttp_uri_get_host(http_uri); 203 if (host == NULL) { 204 die("url must have a host"); 205 } 206 207 port = evhttp_uri_get_port(http_uri); 208 if (port == -1) { 209 port = (strcasecmp(scheme, "http") == 0) ? 80 : 443; 210 } 211 212 path = evhttp_uri_get_path(http_uri); 213 if (path == NULL) { 214 path = "/"; 215 } 216 217 query = evhttp_uri_get_query(http_uri); 218 if (query == NULL) { 219 snprintf(uri, sizeof(uri) - 1, "%s", path); 220 } else { 221 snprintf(uri, sizeof(uri) - 1, "%s?%s", path, query); 222 } 223 uri[sizeof(uri) - 1] = '\0'; 224 225 // Initialize OpenSSL 226 SSL_library_init(); 227 ERR_load_crypto_strings(); 228 SSL_load_error_strings(); 229 OpenSSL_add_all_algorithms(); 230 231 /* This isn't strictly necessary... OpenSSL performs RAND_poll 232 * automatically on first use of random number generator. */ 233 r = RAND_poll(); 234 if (r == 0) { 235 die_openssl("RAND_poll"); 236 } 237 238 /* Create a new OpenSSL context */ 239 ssl_ctx = SSL_CTX_new(SSLv23_method()); 240 if (!ssl_ctx) 241 die_openssl("SSL_CTX_new"); 242 243 /* Attempt to use the system's trusted root certificates. 244 * (This path is only valid for Debian-based systems.) */ 245 if (1 != SSL_CTX_load_verify_locations(ssl_ctx, 246 "/etc/ssl/certs/ca-certificates.crt", 247 NULL)) 248 die_openssl("SSL_CTX_load_verify_locations"); 249 /* Ask OpenSSL to verify the server certificate. Note that this 250 * does NOT include verifying that the hostname is correct. 251 * So, by itself, this means anyone with any legitimate 252 * CA-issued certificate for any website, can impersonate any 253 * other website in the world. This is not good. See "The 254 * Most Dangerous Code in the World" article at 255 * https://crypto.stanford.edu/~dabo/pubs/abstracts/ssl-client-bugs.html 256 */ 257 SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); 258 /* This is how we solve the problem mentioned in the previous 259 * comment. We "wrap" OpenSSL's validation routine in our 260 * own routine, which also validates the hostname by calling 261 * the code provided by iSECPartners. Note that even though 262 * the "Everything You've Always Wanted to Know About 263 * Certificate Validation With OpenSSL (But Were Afraid to 264 * Ask)" paper from iSECPartners says very explicitly not to 265 * call SSL_CTX_set_cert_verify_callback (at the bottom of 266 * page 2), what we're doing here is safe because our 267 * cert_verify_callback() calls X509_verify_cert(), which is 268 * OpenSSL's built-in routine which would have been called if 269 * we hadn't set the callback. Therefore, we're just 270 * "wrapping" OpenSSL's routine, not replacing it. */ 271 SSL_CTX_set_cert_verify_callback (ssl_ctx, cert_verify_callback, 272 (void *) host); 273 274 // Create event base 275 base = event_base_new(); 276 if (!base) { 277 perror("event_base_new()"); 278 return 1; 279 } 280 281 // Create OpenSSL bufferevent and stack evhttp on top of it 282 ssl = SSL_new(ssl_ctx); 283 if (ssl == NULL) { 284 die_openssl("SSL_new()"); 285 } 286 287 if (strcasecmp(scheme, "http") == 0) { 288 bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); 289 } else { 290 bev = bufferevent_openssl_socket_new(base, -1, ssl, 291 BUFFEREVENT_SSL_CONNECTING, 292 BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS); 293 } 294 295 if (bev == NULL) { 296 fprintf(stderr, "bufferevent_openssl_socket_new() failed\n"); 297 return 1; 298 } 299 300 bufferevent_openssl_set_allow_dirty_shutdown(bev, 1); 301 302 // For simplicity, we let DNS resolution block. Everything else should be 303 // asynchronous though. 304 evcon = evhttp_connection_base_bufferevent_new(base, NULL, bev, 305 host, port); 306 if (evcon == NULL) { 307 fprintf(stderr, "evhttp_connection_base_bufferevent_new() failed\n"); 308 return 1; 309 } 310 311 // Fire off the request 312 req = evhttp_request_new(http_request_done, bev); 313 if (req == NULL) { 314 fprintf(stderr, "evhttp_request_new() failed\n"); 315 return 1; 316 } 317 318 output_headers = evhttp_request_get_output_headers(req); 319 evhttp_add_header(output_headers, "Host", host); 320 evhttp_add_header(output_headers, "Connection", "close"); 321 322 r = evhttp_make_request(evcon, req, EVHTTP_REQ_GET, uri); 323 if (r != 0) { 324 fprintf(stderr, "evhttp_make_request() failed\n"); 325 return 1; 326 } 327 328 event_base_dispatch(base); 329 330 evhttp_connection_free(evcon); 331 event_base_free(base); 332 333 return 0; 334 } 335