4 * Copyright (C) 2011 Simon Ruderich
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #include "connection.h"
34 /* Maximum line of a HTTP request line. Longer request lines are aborted with
35 * an error. The standard doesn't specify a maximum line length but this
36 * should be a good limit to make processing simpler. */
37 #define MAX_REQUEST_LINE 4096
39 /* Format string used to send HTTP/1.0 error responses to the client.
41 * %s is used 4 times, first three are the error code (no %n$s!), the last is
43 #define HTTP_RESPONSE_FORMAT "HTTP/1.0 %s\r\n\
44 Content-Type: text/html; charset=US-ASCII\r\n\
46 <!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n\
48 <head><title>%s</title></head>\n\
56 static int initialize_tls_session_client(int peer_socket,
58 gnutls_session_t *session,
59 gnutls_certificate_credentials_t *x509_cred);
60 static int initialize_tls_session_server(int peer_socket,
61 gnutls_session_t *session,
62 gnutls_certificate_credentials_t *x509_cred);
64 static int read_http_request(FILE *client_fd, char *request, size_t length);
65 static void send_bad_request(FILE *client_fd);
66 static void send_forwarding_failure(FILE *client_fd);
67 static void tls_send_invalid_cert_message(gnutls_session_t session);
69 static void transfer_data(int client, int server);
70 static int read_from_write_to(int from, int to);
71 static void transfer_data_tls(int client, int server,
72 gnutls_session_t client_session,
73 gnutls_session_t server_session);
74 static int read_from_write_to_tls(gnutls_session_t from, gnutls_session_t to);
76 static int connect_to_host(const char *hostname, const char *port);
78 static int parse_request(const char *buffer, char *host, char *port,
82 void handle_connection(int client_socket) {
84 FILE *client_fd, *server_fd;
86 char buffer[MAX_REQUEST_LINE];
87 char host[MAX_REQUEST_LINE];
90 int version_minor; /* HTTP/1.x */
93 /* client_x509_cred is used when talking to the client (acting as a TSL
94 * server), server_x509_cred is used when talking to the server (acting as
96 gnutls_certificate_credentials_t client_x509_cred, server_x509_cred;
98 gnutls_session_t client_session, server_session;
99 /* initialize_tls_session_*() called? - used for goto out */
100 int client_session_init, server_session_init;
101 /* gnutls_handshake() called? - used for goto out */
102 int client_session_started, server_session_started;
103 /* Validation failed? If yes we need to send the special "invalid"
105 int validation_failed;
107 LOG(LOG_DEBUG, "new connection");
112 client_session_init = 0;
113 server_session_init = 0;
114 client_session_started = 0;
115 server_session_started = 0;
116 validation_failed = 0;
118 client_fd = fdopen(client_socket, "a+");
119 if (NULL == client_fd) {
120 LOG_PERROR(LOG_WARNING, "fdopen(): client failed");
124 /* Read request line (CONNECT ..) and headers (they are discarded). */
125 result = read_http_request(client_fd, buffer, sizeof(buffer));
128 LOG(LOG_WARNING, "read_http_request(): client read error");
130 } else if (-2 == result) {
132 LOG(LOG_WARNING, "read_http_request(): client EOF");
133 send_bad_request(client_fd);
137 if (0 != parse_request(buffer, host, port, &version_minor)) {
138 LOG(LOG_WARNING, "bad request: %s", buffer);
139 send_bad_request(client_fd);
143 LOG(LOG_DEBUG, "target: %s:%s (HTTP 1.%d)", host, port, version_minor);
145 /* Connect to proxy server or directly to server. */
146 if (NULL != global_proxy_host && NULL != global_proxy_port) {
147 LOG(LOG_DEBUG, "connecting to %s:%s", global_proxy_host,
149 server_socket = connect_to_host(global_proxy_host, global_proxy_port);
151 LOG(LOG_DEBUG, "connecting to %s:%s", host, port);
152 server_socket = connect_to_host(host, port);
155 if (-1 == server_socket) {
156 LOG(LOG_WARNING, "failed to connect to server");
157 send_forwarding_failure(client_fd);
160 server_fd = fdopen(server_socket, "a+");
161 if (NULL == server_fd) {
162 LOG_PERROR(LOG_WARNING, "fdopen(): server failed");
163 send_forwarding_failure(client_fd);
167 /* Connect to proxy if requested (command line option). */
168 if (NULL != global_proxy_host && NULL != global_proxy_port) {
169 fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
170 fprintf(server_fd, "\r\n");
172 /* Read response line from proxy server. */
173 result = read_http_request(server_fd, buffer, sizeof(buffer));
176 LOG(LOG_WARNING, "read_http_request(): proxy read error");
177 send_forwarding_failure(client_fd);
179 } else if (-2 == result) {
181 LOG(LOG_WARNING, "read_http_request(): proxy EOF");
182 send_forwarding_failure(client_fd);
186 /* Check response of proxy server. */
187 if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
188 LOG(LOG_WARNING, "bad proxy response: %s", buffer);
189 send_forwarding_failure(client_fd);
194 LOG(LOG_DEBUG, "connection to server established");
196 /* If the -u option is used and we don't know this hostname's server
197 * certificate then just pass through the connection and let the client
198 * verify the server certificate. */
199 if (global_passthrough_unknown) {
203 if (-2 == server_certificate_path(&file, host, path, sizeof(path))) {
204 /* We've established a connection, tell the client. */
205 fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
206 fprintf(client_fd, "\r\n");
209 LOG(LOG_DEBUG, "transferring data");
211 /* Proxy data between client and server until one side is done
213 transfer_data(client_socket, server_socket);
215 LOG(LOG_DEBUG, "finished transferring data");
219 /* server_certificate_path() may open the file, close it. */
225 /* Initialize TLS client credentials to talk to the server. */
226 result = initialize_tls_session_server(server_socket, &server_session,
229 LOG(LOG_WARNING, "initialize_tls_session_server() failed");
230 send_forwarding_failure(client_fd);
233 server_session_init = 1;
235 LOG(LOG_DEBUG, "starting server TLS handshake");
237 /* Try to establish TLS handshake between us and server. */
238 result = gnutls_handshake(server_session);
239 if (GNUTLS_E_SUCCESS != result) {
240 LOG(LOG_WARNING, "server TLS handshake failed: %s",
241 gnutls_strerror(result));
242 send_forwarding_failure(client_fd);
245 server_session_started = 1;
247 LOG(LOG_DEBUG, "server TLS handshake finished");
249 /* Make sure the server certificate is valid and known. */
250 if (0 != verify_tls_connection(server_session, host)) {
251 LOG(LOG_ERROR, "server certificate validation failed!");
252 /* We send the error message over our TLS connection to the client,
253 * but with an invalid certificate. No data is transfered from/to the
255 validation_failed = 1;
258 /* Initialize TLS server credentials to talk to the client. */
259 result = initialize_tls_session_client(client_socket,
260 /* use special host if the server
261 * certificate was invalid */
262 (validation_failed) ? "invalid"
267 LOG(LOG_WARNING, "initialize_tls_session_client() failed");
268 send_forwarding_failure(client_fd);
271 client_session_init = 1;
273 /* We've established a connection, tell the client. */
274 fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
275 fprintf(client_fd, "\r\n");
278 LOG(LOG_DEBUG, "starting client TLS handshake");
280 /* Try to establish TLS handshake between client and us. */
281 result = gnutls_handshake(client_session);
282 if (GNUTLS_E_SUCCESS != result) {
283 LOG(LOG_WARNING, "client TLS handshake failed: %s",
284 gnutls_strerror(result));
285 send_forwarding_failure(client_fd);
288 client_session_started = 1;
290 LOG(LOG_DEBUG, "client TLS handshake finished");
292 /* Tell the client that the verification failed. Shouldn't be necessary as
293 * the client should terminate the connection because he received the
294 * invalid certificate but better be sure. */
295 if (validation_failed) {
296 tls_send_invalid_cert_message(client_session);
300 LOG(LOG_DEBUG, "transferring TLS data");
302 /* Proxy data between client and server until one side is done (EOF or
304 transfer_data_tls(client_socket, server_socket,
305 client_session, server_session);
307 LOG(LOG_DEBUG, "finished transferring TLS data");
310 /* Close TLS sessions if necessary. Use GNUTLS_SHUT_RDWR so the data is
311 * reliable transmitted. */
312 if (0 != server_session_started) {
313 gnutls_bye(server_session, GNUTLS_SHUT_RDWR);
315 if (0 != client_session_started) {
316 gnutls_bye(client_session, GNUTLS_SHUT_RDWR);
318 if (0 != server_session_init) {
319 gnutls_deinit(server_session);
320 gnutls_certificate_free_credentials(server_x509_cred);
322 if (0 != client_session_init) {
323 gnutls_deinit(client_session);
324 gnutls_certificate_free_cas(client_x509_cred);
325 gnutls_certificate_free_keys(client_x509_cred);
326 gnutls_certificate_free_credentials(client_x509_cred);
329 /* Close connection to server/proxy. */
330 if (NULL != server_fd) {
332 } else if (-1 != server_socket) {
333 close(server_socket);
335 LOG(LOG_DEBUG, "connection to server closed");
336 /* Close connection to client. */
337 if (NULL != client_fd) {
340 close(client_socket);
342 LOG(LOG_DEBUG, "connection to client closed");
344 LOG(LOG_DEBUG, "connection finished");
348 static int initialize_tls_session_client(int peer_socket,
349 const char *hostname,
350 gnutls_session_t *session,
351 gnutls_certificate_credentials_t *x509_cred) {
353 int use_invalid_cert;
356 /* The "invalid" hostname is special. If it's used we send an invalid
357 * certificate to let the client know something is wrong. */
358 use_invalid_cert = 0 == strcmp(hostname, "invalid");
360 /* Hostname too long. */
361 if (sizeof(path) - strlen(PROXY_SERVER_CERT_FORMAT) <= strlen(hostname)) {
363 "initialize_tls_session_client(): hostname too long: '%s'",
367 /* Try to prevent path traversals in hostnames. */
368 if (NULL != strstr(hostname, "..")) {
370 "initialize_tls_session_client(): possible path traversal: '%s'",
374 snprintf(path, sizeof(path), PROXY_SERVER_CERT_FORMAT, hostname);
376 result = gnutls_certificate_allocate_credentials(x509_cred);
377 if (GNUTLS_E_SUCCESS != result) {
379 "initialize_tls_session_client(): \
380 gnutls_certificate_allocate_credentials(): %s",
381 gnutls_strerror(result));
385 /* Load proxy CA file, this CA "list" is send to the client. */
386 if (!use_invalid_cert) {
387 result = gnutls_certificate_set_x509_trust_file(*x509_cred,
389 GNUTLS_X509_FMT_PEM);
390 /* If the invalid hostname was specified do nothing, we use a self-signed
391 * certificate in this case. */
397 "initialize_tls_session_client(): can't read CA file: '%s'",
399 gnutls_certificate_free_credentials(*x509_cred);
402 /* And certificate for this website and proxy's private key. */
403 if (!use_invalid_cert) {
404 result = gnutls_certificate_set_x509_key_file(*x509_cred,
405 path, PROXY_KEY_FILE,
406 GNUTLS_X509_FMT_PEM);
407 /* If the invalid hostname was specified load our special "invalid"
410 result = gnutls_certificate_set_x509_key_file(*x509_cred,
411 PROXY_INVALID_CERT_FILE,
413 GNUTLS_X509_FMT_PEM);
415 if (GNUTLS_E_SUCCESS != result) {
417 "initialize_tls_session_client(): \
418 can't read server certificate ('%s') or key file ('%s'): %s",
419 path, PROXY_KEY_FILE, gnutls_strerror(result));
420 gnutls_certificate_free_credentials(*x509_cred);
421 /* Could be a missing certificate. */
425 gnutls_certificate_set_dh_params(*x509_cred, global_tls_dh_params);
427 result = gnutls_init(session, GNUTLS_SERVER);
428 if (GNUTLS_E_SUCCESS != result) {
430 "initialize_tls_session_client(): gnutls_init(): %s",
431 gnutls_strerror(result));
432 gnutls_certificate_free_credentials(*x509_cred);
435 result = gnutls_priority_set(*session, global_tls_priority_cache);
436 if (GNUTLS_E_SUCCESS != result) {
438 "initialize_tls_session_client(): gnutls_priority_set(): %s",
439 gnutls_strerror(result));
440 gnutls_deinit(*session);
441 gnutls_certificate_free_credentials(*x509_cred);
444 result = gnutls_credentials_set(*session,
445 GNUTLS_CRD_CERTIFICATE, *x509_cred);
446 if (GNUTLS_E_SUCCESS != result) {
448 "initialize_tls_session_client(): gnutls_credentials_set(): %s",
449 gnutls_strerror(result));
450 gnutls_deinit(*session);
451 gnutls_certificate_free_credentials(*x509_cred);
455 gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
459 static int initialize_tls_session_server(int peer_socket,
460 gnutls_session_t *session,
461 gnutls_certificate_credentials_t *x509_cred) {
464 result = gnutls_certificate_allocate_credentials(x509_cred);
465 if (GNUTLS_E_SUCCESS != result) {
467 "initialize_tls_session_server(): \
468 gnutls_certificate_allocate_credentials(): %s",
469 gnutls_strerror(result));
473 result = gnutls_init(session, GNUTLS_CLIENT);
474 if (GNUTLS_E_SUCCESS != result) {
476 "initialize_tls_session_server(): gnutls_init(): %s",
477 gnutls_strerror(result));
478 gnutls_certificate_free_credentials(*x509_cred);
481 gnutls_priority_set(*session, global_tls_priority_cache);
482 if (GNUTLS_E_SUCCESS != result) {
484 "initialize_tls_session_server(): gnutls_priority_set(): %s",
485 gnutls_strerror(result));
486 gnutls_deinit(*session);
487 gnutls_certificate_free_credentials(*x509_cred);
490 result = gnutls_credentials_set(*session,
491 GNUTLS_CRD_CERTIFICATE, *x509_cred);
492 if (GNUTLS_E_SUCCESS != result) {
494 "initialize_tls_session_server(): gnutls_credentials_set(): %s",
495 gnutls_strerror(result));
496 gnutls_deinit(*session);
497 gnutls_certificate_free_credentials(*x509_cred);
501 gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
507 /* Read HTTP request line and headers (ignored).
509 * On success 0 is returned, -1 on client error, -2 on unexpected EOF.
511 static int read_http_request(FILE *client_fd, char *request, size_t length) {
512 char buffer[MAX_REQUEST_LINE];
514 if (NULL == fgets(request, (int)length, client_fd)) {
515 if (ferror(client_fd)) {
516 LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
523 while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
525 if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
529 if (ferror(client_fd)) {
530 LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
537 static void send_bad_request(FILE *client_fd) {
538 #define RESPONSE_ERROR "400 Bad Request"
539 #define RESPONSE_MSG "Your browser sent an invalid request."
540 fprintf(client_fd, HTTP_RESPONSE_FORMAT,
541 RESPONSE_ERROR, RESPONSE_ERROR, RESPONSE_ERROR,
543 #undef RESPONSE_ERROR
546 static void send_forwarding_failure(FILE *client_fd) {
547 #define RESPONSE_ERROR "503 Forwarding failure"
548 #define RESPONSE_MSG "Failed to connect to server, check logs."
549 fprintf(client_fd, HTTP_RESPONSE_FORMAT,
550 RESPONSE_ERROR, RESPONSE_ERROR, RESPONSE_ERROR,
552 #undef RESPONSE_ERROR
555 static void tls_send_invalid_cert_message(gnutls_session_t session) {
556 #define RESPONSE_ERROR "500 Internal Server Error"
557 #define RESPONSE_MSG "Server certificate validation failed, check logs."
559 char buffer[sizeof(HTTP_RESPONSE_FORMAT) - 1 /* '\0' */
560 - 4 * 2 /* four %s */
561 + (sizeof(RESPONSE_ERROR) - 1 /* '\0' */) * 3
562 + sizeof(RESPONSE_MSG) - 1 /* '\0' */
565 snprintf(buffer, sizeof(buffer),
566 HTTP_RESPONSE_FORMAT,
567 RESPONSE_ERROR, RESPONSE_ERROR, RESPONSE_ERROR, RESPONSE_MSG);
569 gnutls_record_send(session, buffer, sizeof(buffer) - 1);
570 /* don't send trailing '\0' */
571 #undef RESPONSE_ERROR
576 /* Transfer data between client and server sockets until one closes the
578 static void transfer_data(int client, int server) {
579 struct pollfd fds[2];
581 fds[0].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
584 fds[1].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
588 int result = poll(fds, 2, -1 /* no timeout */);
590 LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
594 /* Data available from client. */
595 if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
596 if (0 != read_from_write_to(client, server)) {
597 /* EOF (or other error) */
601 /* Data available from server. */
602 if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
603 if (0 != read_from_write_to(server, client)) {
604 /* EOF (or other error) */
609 /* Client closed connection. */
610 if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
613 /* Server closed connection. */
614 if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
620 /* Read available data from socket from and write it to socket to. At maximum
621 * 4096 bytes are read/written. */
622 static int read_from_write_to(int from, int to) {
624 ssize_t size_written;
627 LOG(LOG_DEBUG, "read_from_write_to(): %d -> %d", from, to);
629 size_read = read(from, buffer, sizeof(buffer));
631 LOG_PERROR(LOG_WARNING, "read_from_write_to(): read()");
635 if (0 == size_read) {
639 size_written = write(to, buffer, (size_t)size_read);
640 if (0 > size_written) {
641 LOG_PERROR(LOG_WARNING, "read_from_write_to(): write()");
644 if (size_read != size_written) {
645 LOG(LOG_ERROR, "read_from_write_to(): only written %ld of %ld bytes!",
646 (long int)size_written, (long int)size_read);
653 /* Transfer data between client and server TLS connection until one closes the
655 static void transfer_data_tls(int client, int server,
656 gnutls_session_t client_session,
657 gnutls_session_t server_session) {
658 struct pollfd fds[2];
660 fds[0].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
663 fds[1].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
667 int result = poll(fds, 2, -1 /* no timeout */);
669 LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
673 /* Data available from client. */
674 if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
675 if (0 != read_from_write_to_tls(client_session, server_session)) {
676 /* EOF (or other error) */
680 /* Data available from server. */
681 if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
682 if (0 != read_from_write_to_tls(server_session, client_session)) {
683 /* EOF (or other error) */
688 /* Client closed connection. */
689 if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
692 /* Server closed connection. */
693 if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
699 /* Read available data from session from and write to session to. */
700 static int read_from_write_to_tls(gnutls_session_t from,
701 gnutls_session_t to) {
704 ssize_t size_written;
707 /* Get maximum possible buffer size. */
708 size = gnutls_record_get_max_size(from);
709 LOG(LOG_DEBUG, "read_from_write_to_tls(): suggested buffer size: %ld",
711 if (size > gnutls_record_get_max_size(to)) {
712 size = gnutls_record_get_max_size(to);
714 if (size > sizeof(buffer)) {
715 size = sizeof(buffer);
717 LOG(LOG_DEBUG, "read_from_write_to_tls(): used buffer size: %ld",
720 size_read = gnutls_record_recv(from, buffer, size);
722 LOG(LOG_WARNING, "read_from_write_to_tls(): gnutls_record_recv(): %s",
723 gnutls_strerror((int)size_read));
727 if (0 == size_read) {
731 size_written = gnutls_record_send(to, buffer, (size_t)size_read);
732 if (0 > size_written) {
733 LOG(LOG_WARNING, "read_from_write_to_tls(): gnutls_record_send(): %s",
734 gnutls_strerror((int)size_written));
737 if (size_read != size_written) {
738 LOG(LOG_ERROR, "read_from_write_to_tls(): only written %ld of %ld bytes!",
739 (long int)size_written, (long int)size_read);
747 static int connect_to_host(const char *hostname, const char *port) {
748 struct addrinfo gai_hints;
749 struct addrinfo *gai_result;
753 struct addrinfo *server;
755 if (NULL == hostname || NULL == port) {
759 /* Get IP of hostname server. */
760 memset(&gai_hints, 0, sizeof(gai_hints));
761 gai_hints.ai_family = AF_UNSPEC;
762 gai_hints.ai_socktype = SOCK_STREAM;
763 gai_hints.ai_protocol = 0;
764 gai_hints.ai_flags = AI_NUMERICSERV /* given port is numeric */
765 | AI_ADDRCONFIG /* supported by this computer */
766 | AI_V4MAPPED; /* support IPv4 through IPv6 */
767 gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
768 if (0 != gai_return) {
769 LOG_PERROR(LOG_WARNING, "connect_to_host(): getaddrinfo()");
773 /* Now try to connect to each server returned by getaddrinfo(), use the
774 * first successful connect. */
775 for (server = gai_result; NULL != server; server = server->ai_next) {
776 server_socket = socket(server->ai_family,
778 server->ai_protocol);
779 if (-1 == server_socket) {
780 LOG_PERROR(LOG_DEBUG, "connect_to_host(): socket(), trying next");
784 if (-1 != connect(server_socket, server->ai_addr,
785 server->ai_addrlen)) {
788 LOG_PERROR(LOG_DEBUG, "connect_to_host(): connect(), trying next");
790 close(server_socket);
792 /* Make sure we free the result from getaddrinfo(). */
793 freeaddrinfo(gai_result);
795 if (NULL == server) {
796 LOG_PERROR(LOG_WARNING, "connect_to_host(): no server found, abort");
800 return server_socket;
804 /* Parse HTTP CONNECT request string and save its parameters.
806 * The following format is expected: "CONNECT host:port HTTP/1.x".
808 * request and host must have the same size! port must be at least 6 bytes
811 static int parse_request(const char *request, char *host, char *port,
812 int *version_minor) {
813 int port_unused; /* just used to verify the port is numeric */
816 /* scanf() doesn't check spaces. */
817 if (0 != strncmp(request, "CONNECT ", 8)) {
820 /* Check request and extract data, "host:port" is not yet separated. */
821 if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
822 host, version_minor)) {
825 /* Make sure ":port" is there. */
826 if (NULL == (position = strchr(host, ':'))) {
829 /* Make sure port is numeric. */
830 if (1 != sscanf(position + 1, "%d", &port_unused)) {
833 /* Store it in *port. */
834 strncpy(port, position + 1, 5);
836 /* And remove port from host. */