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
40 static int initialize_tls_session_client(int peer_socket,
42 gnutls_session_t *session,
43 gnutls_certificate_credentials_t *x509_cred);
44 static int initialize_tls_session_server(int peer_socket,
45 gnutls_session_t *session,
46 gnutls_certificate_credentials_t *x509_cred);
48 static int read_http_request(FILE *client_fd, char *request, size_t length);
49 static void send_bad_request(FILE *client_fd);
50 static void send_forwarding_failure(FILE *client_fd);
51 static void tls_send_invalid_cert_message(gnutls_session_t session);
54 static void transfer_data(int client, int server);
55 static int read_from_write_to(int from, int to);
57 static void transfer_data_tls(int client, int server,
58 gnutls_session_t client_session,
59 gnutls_session_t server_session);
60 static int read_from_write_to_tls(gnutls_session_t from, gnutls_session_t to);
62 static int connect_to_host(const char *hostname, const char *port);
64 static int parse_request(const char *buffer, char *host, char *port,
68 void handle_connection(int client_socket) {
70 FILE *client_fd, *server_fd;
72 char buffer[MAX_REQUEST_LINE];
73 char host[MAX_REQUEST_LINE];
79 /* client_x509_cred is used when talking to the client (acting as a TSL
80 * server), server_x509_cred is used when talking to the server (acting as
82 gnutls_certificate_credentials_t client_x509_cred, server_x509_cred;
84 gnutls_session_t client_session, server_session;
85 /* initialize_tls_session_*() called? - used for goto out */
86 int client_session_init, server_session_init;
87 /* gnutls_handshake() called? - used for goto out */
88 int client_session_started, server_session_started;
89 /* Validation failed? If yes we need to send the special "invalid"
91 int validation_failed;
93 LOG(LOG_DEBUG, "new connection");
98 client_session_init = 0;
99 server_session_init = 0;
100 client_session_started = 0;
101 server_session_started = 0;
102 validation_failed = 0;
104 client_fd = fdopen(client_socket, "a+");
105 if (NULL == client_fd) {
106 LOG_PERROR(LOG_WARNING, "fdopen(): client failed");
110 /* Read request line (CONNECT ..) and headers (they are discarded). */
111 result = read_http_request(client_fd, buffer, sizeof(buffer));
114 LOG(LOG_WARNING, "read_http_request(): client read error");
116 } else if (-2 == result) {
118 LOG(LOG_WARNING, "read_http_request(): client EOF");
119 send_bad_request(client_fd);
123 if (0 != parse_request(buffer, host, port, &version_minor)) {
124 LOG(LOG_WARNING, "bad request: %s", buffer);
125 send_bad_request(client_fd);
129 LOG(LOG_DEBUG, "target: %s:%s (HTTP 1.%d)", host, port, version_minor);
131 /* Connect to proxy server or directly to server. */
132 if (NULL != global_proxy_host && NULL != global_proxy_port) {
133 LOG(LOG_DEBUG, "connecting to %s:%s", global_proxy_host,
135 server_socket = connect_to_host(global_proxy_host, global_proxy_port);
137 LOG(LOG_DEBUG, "connecting to %s:%s", host, port);
138 server_socket = connect_to_host(host, port);
141 if (-1 == server_socket) {
142 LOG(LOG_WARNING, "failed to connect to server");
143 send_forwarding_failure(client_fd);
146 server_fd = fdopen(server_socket, "a+");
147 if (NULL == server_fd) {
148 LOG_PERROR(LOG_WARNING, "fdopen(): server failed");
149 send_forwarding_failure(client_fd);
153 /* Connect to proxy if requested (command line option). */
154 if (NULL != global_proxy_host && NULL != global_proxy_port) {
155 fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
156 fprintf(server_fd, "\r\n");
158 /* Read response line from proxy server. */
159 result = read_http_request(server_fd, buffer, sizeof(buffer));
162 LOG(LOG_WARNING, "read_http_request(): proxy read error");
163 send_forwarding_failure(client_fd);
165 } else if (-2 == result) {
167 LOG(LOG_WARNING, "read_http_request(): proxy EOF");
168 send_forwarding_failure(client_fd);
172 /* Check response of proxy server. */
173 if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
174 LOG(LOG_WARNING, "bad proxy response: %s", buffer);
175 send_forwarding_failure(client_fd);
180 LOG(LOG_DEBUG, "connection to server established");
182 result = initialize_tls_session_server(server_socket, &server_session,
184 /* Initialize TLS client credentials to talk to the server. */
186 LOG(LOG_WARNING, "initialize_tls_session_server() failed");
187 send_forwarding_failure(client_fd);
190 server_session_init = 1;
192 LOG(LOG_DEBUG, "starting server TLS handshake");
194 /* Try to establish TLS handshake between us and server. */
195 result = gnutls_handshake(server_session);
196 if (GNUTLS_E_SUCCESS != result) {
197 LOG(LOG_WARNING, "server TLS handshake failed: %s",
198 gnutls_strerror(result));
199 send_forwarding_failure(client_fd);
202 server_session_started = 1;
204 LOG(LOG_DEBUG, "server TLS handshake finished");
206 /* Make sure the server certificate is valid and known. */
207 if (0 != verify_tls_connection(server_session, host)) {
208 LOG(LOG_ERROR, "server certificate validation failed!");
209 /* We send the error message over our TLS connection to the client,
210 * but with an invalid certificate. */
211 validation_failed = 1;
214 /* Initialize TLS server credentials to talk to the client. */
215 result = initialize_tls_session_client(client_socket,
216 /* use special host if the server
217 * certificate was invalid */
218 (validation_failed) ? "invalid"
223 LOG(LOG_WARNING, "initialize_tls_session_client() failed");
224 send_forwarding_failure(client_fd);
227 client_session_init = 1;
229 /* We've established a connection, tell the client. */
230 fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
231 fprintf(client_fd, "\r\n");
234 LOG(LOG_DEBUG, "starting client TLS handshake");
236 /* Try to establish TLS handshake between client and us. */
237 result = gnutls_handshake(client_session);
238 if (GNUTLS_E_SUCCESS != result) {
239 LOG(LOG_WARNING, "client TLS handshake failed: %s",
240 gnutls_strerror(result));
241 send_forwarding_failure(client_fd);
244 client_session_started = 1;
246 LOG(LOG_DEBUG, "client TLS handshake finished");
248 /* Tell the client that the verification failed. Shouldn't be necessary as
249 * the client should terminate the connection because he received the
250 * invalid certificate but better be sure. */
251 if (validation_failed) {
252 tls_send_invalid_cert_message(client_session);
256 LOG(LOG_DEBUG, "transferring data");
258 /* Proxy data between client and server until one suite is done (EOF or
260 transfer_data_tls(client_socket, server_socket,
261 client_session, server_session);
263 LOG(LOG_DEBUG, "finished transferring data");
266 /* Close TLS sessions if necessary. Use GNUTLS_SHUT_RDWR so the data is
267 * reliable transmitted. */
268 if (0 != server_session_started) {
269 gnutls_bye(server_session, GNUTLS_SHUT_RDWR);
271 if (0 != client_session_started) {
272 gnutls_bye(client_session, GNUTLS_SHUT_RDWR);
274 if (0 != server_session_init) {
275 gnutls_deinit(server_session);
276 gnutls_certificate_free_credentials(server_x509_cred);
278 if (0 != client_session_init) {
279 gnutls_deinit(client_session);
280 gnutls_certificate_free_cas(client_x509_cred);
281 gnutls_certificate_free_keys(client_x509_cred);
282 gnutls_certificate_free_credentials(client_x509_cred);
285 /* Close connection to server/proxy. */
286 if (NULL != server_fd) {
288 } else if (-1 != server_socket) {
289 close(server_socket);
291 LOG(LOG_DEBUG, "connection to server closed");
292 /* Close connection to client. */
293 if (NULL != client_fd) {
296 close(client_socket);
298 LOG(LOG_DEBUG, "connection to client closed");
300 LOG(LOG_DEBUG, "connection finished");
304 static int initialize_tls_session_client(int peer_socket,
305 const char *hostname,
306 gnutls_session_t *session,
307 gnutls_certificate_credentials_t *x509_cred) {
309 int use_invalid_cert;
312 /* The "invalid" hostname is special. If it's used we send an invalid
313 * certificate to let the client know something is wrong. */
314 use_invalid_cert = 0 == strcmp(hostname, "invalid");
316 /* Hostname too long. */
317 if (sizeof(path) - strlen(PROXY_SERVER_CERT_FORMAT) <= strlen(hostname)) {
319 "initialize_tls_session_client(): hostname too long: '%s'",
323 /* Try to prevent path traversals in hostnames. */
324 if (NULL != strstr(hostname, "..")) {
326 "initialize_tls_session_client(): possible path traversal: '%s'",
330 snprintf(path, sizeof(path), PROXY_SERVER_CERT_FORMAT, hostname);
332 result = gnutls_certificate_allocate_credentials(x509_cred);
333 if (GNUTLS_E_SUCCESS != result) {
335 "initialize_tls_session_client(): \
336 gnutls_certificate_allocate_credentials(): %s",
337 gnutls_strerror(result));
341 /* Load proxy CA file, this CA "list" is send to the client. */
342 if (!use_invalid_cert) {
343 result = gnutls_certificate_set_x509_trust_file(*x509_cred,
345 GNUTLS_X509_FMT_PEM);
346 /* If the invalid hostname was specified do nothing, we use a self-signed
347 * certificate in this case. */
353 "initialize_tls_session_client(): can't read CA file: '%s'",
357 /* And certificate for this website and proxy's private key. */
358 if (!use_invalid_cert) {
359 result = gnutls_certificate_set_x509_key_file(*x509_cred,
360 path, PROXY_KEY_FILE,
361 GNUTLS_X509_FMT_PEM);
362 /* If the invalid hostname was specified load our special "invalid"
365 result = gnutls_certificate_set_x509_key_file(*x509_cred,
366 PROXY_INVALID_CERT_FILE,
368 GNUTLS_X509_FMT_PEM);
370 if (GNUTLS_E_SUCCESS != result) {
372 "initialize_tls_session_client(): \
373 can't read server certificate ('%s') or key file ('%s'): %s",
374 path, PROXY_KEY_FILE, gnutls_strerror(result));
375 /* Could be a missing certificate. */
379 gnutls_certificate_set_dh_params(*x509_cred, tls_dh_params);
381 result = gnutls_init(session, GNUTLS_SERVER);
382 if (GNUTLS_E_SUCCESS != result) {
384 "initialize_tls_session_client(): gnutls_init(): %s",
385 gnutls_strerror(result));
388 result = gnutls_priority_set(*session, tls_priority_cache);
389 if (GNUTLS_E_SUCCESS != result) {
391 "initialize_tls_session_client(): gnutls_priority_set(): %s",
392 gnutls_strerror(result));
395 result = gnutls_credentials_set(*session,
396 GNUTLS_CRD_CERTIFICATE, *x509_cred);
397 if (GNUTLS_E_SUCCESS != result) {
399 "initialize_tls_session_client(): gnutls_credentials_set(): %s",
400 gnutls_strerror(result));
404 gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
408 static int initialize_tls_session_server(int peer_socket,
409 gnutls_session_t *session,
410 gnutls_certificate_credentials_t *x509_cred) {
413 result = gnutls_certificate_allocate_credentials(x509_cred);
414 if (GNUTLS_E_SUCCESS != result) {
416 "initialize_tls_session_server(): \
417 gnutls_certificate_allocate_credentials(): %s",
418 gnutls_strerror(result));
422 result = gnutls_init(session, GNUTLS_CLIENT);
423 if (GNUTLS_E_SUCCESS != result) {
425 "initialize_tls_session_server(): gnutls_init(): %s",
426 gnutls_strerror(result));
429 gnutls_priority_set(*session, tls_priority_cache);
430 if (GNUTLS_E_SUCCESS != result) {
432 "initialize_tls_session_server(): gnutls_priority_set(): %s",
433 gnutls_strerror(result));
436 result = gnutls_credentials_set(*session,
437 GNUTLS_CRD_CERTIFICATE, *x509_cred);
438 if (GNUTLS_E_SUCCESS != result) {
440 "initialize_tls_session_server(): gnutls_credentials_set(): %s",
441 gnutls_strerror(result));
445 gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
451 /* Read HTTP request line and headers (ignored).
453 * On success 0 is returned, -1 on client error, -2 on unexpected EOF.
455 static int read_http_request(FILE *client_fd, char *request, size_t length) {
456 char buffer[MAX_REQUEST_LINE];
458 if (NULL == fgets(request, (int)length, client_fd)) {
459 if (ferror(client_fd)) {
460 LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
467 while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
469 if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
473 if (ferror(client_fd)) {
474 LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
481 static void send_bad_request(FILE *client_fd) {
482 fprintf(client_fd, "HTTP/1.0 400 Bad Request\r\n");
483 fprintf(client_fd, "\r\n");
485 static void send_forwarding_failure(FILE *client_fd) {
486 fprintf(client_fd, "HTTP/1.0 503 Forwarding failure\r\n");
487 fprintf(client_fd, "\r\n");
489 static void tls_send_invalid_cert_message(gnutls_session_t session) {
490 gnutls_record_send(session, "HTTP/1.0 500 Internal Server Error\r\n", 36);
491 gnutls_record_send(session, "\r\n", 2);
496 /* Transfer data between client and server sockets until one closes the
498 static void transfer_data(int client, int server) {
499 struct pollfd fds[2];
501 fds[0].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
504 fds[1].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
508 int result = poll(fds, 2, -1 /* no timeout */);
510 LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
514 /* Data available from client. */
515 if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
516 if (0 != read_from_write_to(client, server)) {
517 /* EOF (or other error) */
521 /* Data available from server. */
522 if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
523 if (0 != read_from_write_to(server, client)) {
524 /* EOF (or other error) */
529 /* Client closed connection. */
530 if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
533 /* Server closed connection. */
534 if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
540 /* Read available data from socket from and write it to socket to. At maximum
541 * 4096 bytes are read/written. */
542 static int read_from_write_to(int from, int to) {
544 ssize_t size_written;
547 size_read = read(from, buffer, sizeof(buffer));
549 LOG_PERROR(LOG_WARNING, "read_from_write_to(): read()");
553 if (0 == size_read) {
557 size_written = write(to, buffer, (size_t)size_read);
558 if (0 > size_written) {
559 LOG_PERROR(LOG_WARNING, "read_from_write_to(): write()");
562 if (size_read != size_written) {
563 LOG(LOG_ERROR, "read_from_write_to(): only written %ld of %ld bytes!",
564 (long int)size_written, (long int)size_read);
572 /* Transfer data between client and server TLS connection until one closes the
574 static void transfer_data_tls(int client, int server,
575 gnutls_session_t client_session,
576 gnutls_session_t server_session) {
577 struct pollfd fds[2];
579 fds[0].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
582 fds[1].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
586 int result = poll(fds, 2, -1 /* no timeout */);
588 LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
592 /* Data available from client. */
593 if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
594 if (0 != read_from_write_to_tls(client_session, server_session)) {
595 /* EOF (or other error) */
599 /* Data available from server. */
600 if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
601 if (0 != read_from_write_to_tls(server_session, client_session)) {
602 /* EOF (or other error) */
607 /* Client closed connection. */
608 if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
611 /* Server closed connection. */
612 if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
618 /* Read available data from session from and write to session to. */
619 static int read_from_write_to_tls(gnutls_session_t from,
620 gnutls_session_t to) {
623 ssize_t size_written;
626 /* Get maximum possible buffer size. */
627 size = gnutls_record_get_max_size(from);
628 LOG(LOG_DEBUG, "read_from_write_to_tls(): suggested buffer size: %ld",
630 if (size > gnutls_record_get_max_size(to)) {
631 size = gnutls_record_get_max_size(to);
633 if (size > sizeof(buffer)) {
634 size = sizeof(buffer);
636 LOG(LOG_DEBUG, "read_from_write_to_tls(): used buffer size: %ld",
639 size_read = gnutls_record_recv(from, buffer, size);
641 LOG(LOG_WARNING, "read_from_write_to_tls(): gnutls_record_recv(): %s",
642 gnutls_strerror((int)size_read));
646 if (0 == size_read) {
650 size_written = gnutls_record_send(to, buffer, (size_t)size_read);
651 if (0 > size_written) {
652 LOG(LOG_WARNING, "read_from_write_to_tls(): gnutls_record_send(): %s",
653 gnutls_strerror((int)size_written));
656 if (size_read != size_written) {
657 LOG(LOG_ERROR, "read_from_write_to_tls(): only written %ld of %ld bytes!",
658 (long int)size_written, (long int)size_read);
666 static int connect_to_host(const char *hostname, const char *port) {
667 struct addrinfo gai_hints;
668 struct addrinfo *gai_result;
672 struct addrinfo *server;
674 if (NULL == hostname || NULL == port) {
678 /* Get IP of hostname server. */
679 memset(&gai_hints, 0, sizeof(gai_hints));
680 gai_hints.ai_family = AF_UNSPEC;
681 gai_hints.ai_socktype = SOCK_STREAM;
682 gai_hints.ai_protocol = 0;
683 gai_hints.ai_flags = AI_NUMERICSERV /* given port is numeric */
684 | AI_ADDRCONFIG /* supported by this computer */
685 | AI_V4MAPPED; /* support IPv4 through IPv6 */
686 gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
687 if (0 != gai_return) {
688 LOG_PERROR(LOG_WARNING, "connect_to_host(): getaddrinfo()");
692 /* Now try to connect to each server returned by getaddrinfo(), use the
693 * first successful connect. */
694 for (server = gai_result; NULL != server; server = server->ai_next) {
695 server_socket = socket(server->ai_family,
697 server->ai_protocol);
698 if (-1 == server_socket) {
699 LOG_PERROR(LOG_DEBUG, "connect_to_host(): socket(), trying next");
703 if (-1 != connect(server_socket, server->ai_addr,
704 server->ai_addrlen)) {
707 LOG_PERROR(LOG_DEBUG, "connect_to_host(): connect(), trying next");
709 close(server_socket);
711 /* Make sure we free the result from getaddrinfo(). */
712 freeaddrinfo(gai_result);
714 if (NULL == server) {
715 LOG_PERROR(LOG_WARNING, "connect_to_host(): no server found, abort");
719 return server_socket;
723 /* Parse HTTP CONNECT request string and save its parameters.
725 * The following format is expected: "CONNECT host:port HTTP/1.x".
727 * request and host must have the same size! port must be at least 6 bytes
730 static int parse_request(const char *request, char *host, char *port,
731 int *version_minor) {
732 int port_unused; /* just used to verify the port is numeric */
735 /* scanf() doesn't check spaces. */
736 if (0 != strncmp(request, "CONNECT ", 8)) {
739 /* Check request and extract data, "host:port" is not yet separated. */
740 if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
741 host, version_minor)) {
744 /* Make sure ":port" is there. */
745 if (NULL == (position = strchr(host, ':'))) {
748 /* Make sure port is numeric. */
749 if (1 != sscanf(position + 1, "%d", &port_unused)) {
752 /* Store it in *port. */
753 strncpy(port, position + 1, 5);
755 /* And remove port from host. */